JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

fastrunner and slowrunner trick.(be care of head node)

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode removeNthFromEnd(ListNode head, int n) {
14         // IMPORTANT: Please reset any member data you declared, as
15         // the same Solution instance will be reused for each test case.
16         if(head == null)
17             return null;
18         if(n == 1)
19         {
20             ListNode runner = head;
21             if(runner.next == null)
22                 return null;
23             while(runner.next.next != null)
24                 runner = runner.next;
25             runner.next = null;
26             return head;
27         }
28         
29         ListNode fastrunner = head;
30         ListNode slowrunner = head;
31         while(n > 0)
32         {
33             fastrunner = fastrunner.next;
34             n--;
35             if(fastrunner == null)
36             {
37                 return head.next;
38             }
39         }
40         while(fastrunner.next != null)
41         {
42             slowrunner = slowrunner.next;
43             fastrunner = fastrunner.next;
44         }
45         slowrunner.next = slowrunner.next.next;
46         return head;
47     }
48 }

 

posted on 2013-11-05 14:37  JasonChang  阅读(153)  评论(0编辑  收藏  举报