問題
給出一個單向鏈表,刪除該鏈表倒數第n個節點,並返回頭節點。
例如:
給出鏈表 1->2->3->4->5,n=2
返回鏈表 1->2->3->5
解題思路
最容易想到的算法:
先遍歷一次鏈表,記下鏈表的長度,然後計算倒數第n個節點的下標m,然後再遍歷一次鏈表,移除第m個節點。
這種算法的時間複雜度是O(n^2 )。
有沒有時間複雜度更低的算法呢?答案給是有。
優化後的算法:
定義兩個指針p和q。
p從頭節點開始,遍歷n個節點,然後q從頭節點開始,與p一起繼續向下遍歷,直到p遍歷出鏈表。
此時q所在的節點就是倒數第n個節點了。
此算法的時間複雜度爲O(n)。
爲了方便理解,我畫了下面兩張示意圖。
第一步:
第二步:
代碼
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null || n <= 0) {
return null;
}
ListNode p = head;
ListNode q = head;
int i = 0;
while (i < n) {
p = p.next;
if (p == null) {
head = head.next;
return head;
}
i++;
}
while (p.next != null) {
p = p.next;
q = q.next;
}
q.next = q.next.next;
return head;
}
博文地址
https://www.taowong.com/blog/2018/10/20/data-strutctures-and-algorithm-04.html