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.從尾端刪除第n個節點。
(1)獲取總的鏈表長度,L根據n帶入(L−n+1)求出從第一個節點開始數要刪除的節點。
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);//1、在first節點前增加一個節點,防止僅有一個節點時有誤
dummy.next = head;
int length = 0;
ListNode first = head;
while (first != null) {
length++;//獲取所有節點的長度,包含了加入的判斷節點
first = first.next;
}
length -= n;
first = dummy;
while (length > 0) {
length--;
first = first.next;//循環到要刪除節點的上一個節點
}
first.next = first.next.next;
return dummy.next;//2、返回first節點
}
兩個while循環分別執行L,L-N次,時間複雜度O(L);
(2)分別設定兩個指針,指向頭節點,第一個指針後移n-1,然後再通過第一個指針是否爲空,判斷第二個
指針節點位置,正好爲刪除節點位置。其實跟上邊通過length循環查找時一樣的,都做了length - n次循環
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}