标签:style blog io color ar sp for div on
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.
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 List<ListNode> list = new ArrayList<ListNode>(); 15 ListNode temp = head; 16 if(null == head.next) 17 return null; 18 while(null != temp){ 19 list.add(temp); 20 temp = temp.next; 21 }//只要一趟,把所有节点保存起来 22 23 if(list.size() - n - 1 >= 0){ 24 temp = list.get(list.size() - n - 1); 25 temp.next = temp.next.next; 26 return head; 27 } 28 head = head.next; 29 return head; 30 } 31 }
ps:依然是双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点。博客园上面看到的,就没有实现了
Remove Nth Node From End of List
标签:style blog io color ar sp for div on
原文地址:http://www.cnblogs.com/luckygxf/p/4088042.html