19.Remove Nth Node From End of List
方法1:由于鏈表不能隨機(jī)訪問,所以很自然的想法是第一遍得到鏈表長(zhǎng)度,然后計(jì)算倒數(shù)第n個(gè)結(jié)點(diǎn)的位置,但這樣時(shí)間復(fù)雜度O(n2),想到用空間換取時(shí)間,可以用一個(gè)地址數(shù)組存儲(chǔ)每個(gè)結(jié)點(diǎn)的地址,然后直接刪除掉倒數(shù)第n個(gè),返回頭結(jié)點(diǎn)。
?
方法2:上面的方法雖然時(shí)間復(fù)雜度達(dá)到了線性,但是需要額外的空間,更好的方法是采用雙指針追趕,設(shè)慢指針為pre,快指針為post,先讓post指針走n步,然后pre指針開始走,這樣當(dāng)post走到最后的時(shí)候,pre指針就指向需要?jiǎng)h除結(jié)點(diǎn)的位置,因?yàn)閯h除需要前繼結(jié)點(diǎn)的位置,所以每走一步就需要保存前繼結(jié)點(diǎn),最后需要特殊處理的就是刪除頭結(jié)點(diǎn)的話直接返回第二個(gè)結(jié)點(diǎn)就好了。
遍歷法:
1 class Solution { 2 3 public: 4 5 ListNode*removeNthFromEnd(ListNode* head, int n) { 6 7 ListNode*t[100]; 8 9 int i = 0; 10 11 while (head) 12 13 { 14 15 t[i] =head; 16 17 ++i; 18 19 head =head->next; 20 21 } 22 23 24 25 int p = i -n; 26 27 if (i == 1) 28 29 return NULL; 30 31 else if (p ==0) 32 33 return t[p]->next; 34 35 else 36 37 { 38 39 40 41 t[p -1]->next = t[p]->next; 42 43 return t[0]; 44 45 } 46 47 } 48 49 };
?
?
?????? 雙指針法:
1 /** 2 3 * Definition for singly-linked list. 4 5 * struct ListNode { 6 7 * int val; 8 9 * ListNode *next; 10 11 * ListNode(int x) : val(x), next(NULL) {} 12 13 * }; 14 15 */ 16 17 classSolution { 18 19 public: 20 21 ListNode* removeNthFromEnd(ListNode*head, int n) { 22 23 ListNode*pre = head, *p = head, *t= head; 24 25 for (int i = 0; i < n; i++) 26 27 t = t->next; 28 29 if (!t) 30 31 return head->next; 32 33 else 34 35 { 36 37 while (t) 38 39 { 40 41 t = t->next; 42 43 pre = p; 44 45 p = p->next; 46 47 } 48 49 pre->next = p->next; 50 51 return head; 52 53 } 54 55 56 57 58 59 } 60 61 };
?
轉(zhuǎn)載于:https://www.cnblogs.com/InitialD/p/7348911.html
總結(jié)
以上是生活随笔為你收集整理的19.Remove Nth Node From End of List的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 现在的三七粉多少钱1克?
- 下一篇: MyEclipse设置默认的文档注释和背