19. Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
Notice
The minimum number of nodes in list is n.
Example
Given linked list: 1->2->3->4->5->null
, and n = 2
.
After removing the second node from the end, the linked list becomes 1->2->3->5->null
.
Challenge
Can you do it without getting the length of the linked list?
分析:
为了删除倒数第n个node,我们需要找到那个node的parent,然后parent.next = parent.next.next. 这里我们创建一个dummy node用来处理删除的是第一个node的情况。
1 public class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 5 ListNode dummy = new ListNode(0); 6 dummy.next = head; 7 8 ListNode parent = dummy; 9 for (int i = 0; i < n; i++) { 10 if (head == null) { 11 return null; 12 } 13 head = head.next; 14 } 15 while (head != null) { 16 head = head.next; 17 parent = parent.next; 18 } 19 parent.next = parent.next.next; 20 return dummy.next; 21 } 22 }
转载请注明出处:cnblogs.com/beiyeqingteng/