首页 > 其他 > 详细

LeetCode: Remove Nth Node From End of List

时间:2014-02-10 13:02:51      阅读:393      评论:0      收藏:0      [点我收藏+]

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

原来的想法很简单,就是先扫描一遍list,判断list的长度,然后从头重新扫描,计算好走多少不,找到要删除的node的前一个node,然后把node.next = node.next.next; 这里需要对list扫描两次。

bubuko.com,布布扣
 1 public ListNode removeNthFromEnd(ListNode head, int n) {
 2         int length = 0;
 3         ListNode tmp = head;
 4         while (tmp != null) {
 5             length++;
 6             tmp = tmp.next;
 7         }
 8         if ( length < n ) return null;
 9         else if (length == n ) {
10             if ( length == 1) return null;
11             else return head.next;
12         }
13         if ( n == 0 ) return head;
14         ListNode c = head;
15         for (int i=0; i<length-n-1; i++) {
16             c = c.next;
17         }
18         
19         c.next = c.next.next;
20         
21         return head;
22     }
bubuko.com,布布扣

 

在网上看到一种方法,不用扫描两次,只需一次。用两个指针,第一个指针先走n步,然后两个指针一起走。当走的快的那个指针到达null的时候,慢的指针恰好 指向需要删除的node的前一个node。而且代码更简洁。

bubuko.com,布布扣
 1 public ListNode removeNthFromEnd(ListNode head, int n) {
 2     // use two pointers,fast pointer forward n steps first
 3     ListNode re=head,fast=head,slow=head;
 4     for(int i=0;i<n;i++) fast=fast.next;
 5     if(fast==null) return head.next; //head node need to be removed
 6     while(fast.next!=null){
 7         fast=fast.next;
 8         slow=slow.next;
 9     }
10     slow.next=slow.next.next;
11     return head;
12   }
bubuko.com,布布扣

LeetCode: Remove Nth Node From End of List

原文:http://www.cnblogs.com/longhorn/p/3542223.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!