Leetcode013--单链表删除操作

来源:互联网 发布:windows字体库在哪 编辑:程序博客网 时间:2024/05/26 20:24

一、原题



Given a linked list, remove the nth node from the end of list and return its head. 



二、中文



删除单链表的倒数第N个结点,注意:输入的N都是合法,在一次遍历中完成操作。



三、举例



比如给出链表 1->2->3->4->5->6->7,当我们删除倒数第三个元素的后就变成了1->2->3->4->6->7



四、思路



思路是先找到第n个元素,同时使用另一个指针指向head结点,这样两个节点以相同的间隔平移到最后,就找到的倒数第n个结点



五、程序


思路是先找到第n个元素,同时使用另一个指针指向
package LeetCode;//删除单链表的倒数第N个结点,注意:输入的N都是合法,在一次遍历中完成操作。 class ListNode {    int val;    ListNode next;        ListNode(){     }    ListNode(int x) {        val = x;        next = null;    }}public class Leetcode014 {public static void main(String args[]){        ListNode n1 = new ListNode(1);          ListNode n2 = new ListNode(2);          ListNode n3 = new ListNode(3);          ListNode n4 = new ListNode(4);          ListNode n5 = new ListNode(5);          ListNode n6 = new ListNode(6);          ListNode n7 = new ListNode(7);            n1.next = n2;          n2.next = n3;          n3.next = n4;          n4.next = n5;          n5.next = n6;          n6.next = n7;  ListNode list = new ListNode();list = reGetKthNode(n1, 3);reversePrintListRec(list);}    public static void reversePrintListRec(ListNode head){          if(head==null)return;          else{          while(head != null){        System.out.print(head.val+" ");        head = head.next;        }        }      }      public static ListNode reGetKthNode(ListNode head,int n){      if(head == null) return null;            ListNode a=head;          ListNode b=head;                 // 找到第n个结点        for (int i = 0; i < n && a != null; i++) {            a = a.next;        }                while(a.next!=null){               a=a.next;              b=b.next;         }          b.next = b.next.next;        return head;      } }

-----------------------------------output---------------------------------------

1 2 3 4 6 7 




1 0
原创粉丝点击