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 這種題目都可以使用fast和slow指針來解決。fast先向前走n步,然後slow和fast再一起走。當fast爲null時,slow就是要刪除的節點。
2 要刪除的節點可能是頭節點,需要單獨判斷一下,或者設置一個dummyNode,指向head,這樣就使head節點和其他節點一樣了。
public class RemoveNthNodeFromEndofList {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null) return null;
//維護一個dummyNode
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode cur = head;
int length = 0;
while(cur!=null) {
cur = cur.next;
length++;
}
if(n>length) return head;
int tmp = length - n;
cur = dummyNode;
while((tmp--)!=0) {
cur = cur.next;
}
//此時的cur是要刪除節點的前面一個節點
cur.next = cur.next.next;
return dummyNode.next;
}
/*
* 這種題目可以使用兩個指針fast slow,一開始fast向前走n步,然後fast和slow再一起走。當fast爲null時,slow指向了要刪除的節點
* 刪除一個節點時,需要一個指針pre指向要刪除節點的前面一個節點,這裏另fast.next==null,此時slow指向要刪除節點的前一個節點,就不需要一個pre指針了
*/
public ListNode removeNthFromEnd2(ListNode head, int n) {
if(head==null) return null;
ListNode fast = head;
ListNode slow = head;
//fast向前走n步
while((n--)!=0) {
fast = fast.next;
}
//fast爲null 表示要刪除的是頭節點
if(fast==null) {
return head.next;
}
//fast slow一起走
while(fast.next!=null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}