Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
也可以用双指针(fast pointer) 来做,但是要注意 n = len的情况。
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 // Note: The Solution object is instantiated only once and is reused by each test case. 15 ListNode per = head; 16 ListNode cur = head; 17 ListNode before = head; 18 int len = 0; 19 while(per != null){ 20 per = per.next; 21 len ++; 22 } 23 int num = len - n; 24 if(num == 0)return head.next; 25 else{ 26 per = head; 27 for(int i = 0; i < num; i ++){ 28 cur = per; 29 per = per.next; 30 } 31 cur.next = per.next; 32 return head; 33 } 34 } 35 }
第二遍:
1 public class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 ListNode header = new ListNode(-1); 5 header.next = head; 6 ListNode cur = header; 7 ListNode per = header; 8 ListNode fast = header; 9 for(int i = 0; i < n; i ++){ 10 fast = fast.next; 11 } 12 while(fast != null){ 13 per = cur; 14 fast = fast.next; 15 cur = cur.next; 16 } 17 per.next = cur.next; 18 return header.next; 19 } 20 }
posted on 2013-10-16 08:05 Step-BY-Step 阅读(155) 评论(0) 编辑 收藏 举报