19. Remove Nth Node From End of List
题目描述
Given a linked list, remove the nth node from the end of
For example,
Note:
Given n will always
解题方法
- Consider that head是否會被remove , 因為有可能,所以create dummy head.
- 因為是從end nth remove, index 從1開始, 所以利用two pointers 從dummy node 走nth node到要被移除的element 前面, 然後two pointers 同步走到底,其中tail pointer 就會走到要被移除的element前面
- Then only manipulate the tail pointer to remove the specified element
public ListNode removeNthFromEnd(ListNode head, int n){
if(head == null || head.next == null || n <= 0){return null;}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
for(int i = 0; i < n; i++){
if(fast == null){
return null;
}
fast = fast.next;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}