C++實現(xiàn)LeetCode(19.移除鏈表倒數(shù)第N個節(jié)點)
[LeetCode] 19. Remove Nth Node From End of List 移除鏈表倒數(shù)第N個節(jié)點
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.
這道題讓我們移除鏈表倒數(shù)第N個節(jié)點,限定n一定是有效的,即n不會大于鏈表中的元素總數(shù)。還有題目要求一次遍歷解決問題,那么就得想些比較巧妙的方法了。比如首先要考慮的時,如何找到倒數(shù)第N個節(jié)點,由于只允許一次遍歷,所以不能用一次完整的遍歷來統(tǒng)計鏈表中元素的個數(shù),而是遍歷到對應位置就應該移除了。那么就需要用兩個指針來幫助解題,pre 和 cur 指針。首先 cur 指針先向前走N步,如果此時 cur 指向空,說明N為鏈表的長度,則需要移除的為首元素,那么此時返回 head->next 即可,如果 cur 存在,再繼續(xù)往下走,此時 pre 指針也跟著走,直到 cur 為最后一個元素時停止,此時 pre 指向要移除元素的前一個元素,再修改指針跳過需要移除的元素即可,參見代碼如下:
方式一:
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if (!head->next) return NULL; ListNode *pre = head, *cur = head; for (int i = 0; i < n; ++i) cur = cur->next; if (!cur) return head->next; while (cur->next) { cur = cur->next; pre = pre->next; } pre->next = pre->next->next; return head; } };
方式二:
class Solution { public: int getLength(ListNode* head) { int length = 0; while (head) { ++length; head = head->next; } return length; } ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* dummy = new ListNode(0, head); int length = getLength(head); ListNode* cur = dummy; for (int i = 1; i < length - n + 1; ++i) { cur = cur->next; } cur->next = cur->next->next; ListNode* ans = dummy->next; delete dummy; return ans; } };
到此這篇關于C++實現(xiàn)LeetCode(19.移除鏈表倒數(shù)第N個節(jié)點)的文章就介紹到這了,更多相關C++實現(xiàn)移除鏈表倒數(shù)第N個節(jié)點內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
內(nèi)聯(lián)函數(shù)inline與宏定義深入解析
類的內(nèi)斂函數(shù)是一個真正的函數(shù)。使用內(nèi)聯(lián)函數(shù)inline可以完全取代表達式形式的宏定義2013-09-09C++ COM編程之QueryInterface函數(shù)(二)
這篇文章主要介紹了C++ COM編程之QueryInterface函數(shù)(二),本文是第二篇,第一篇請參閱相關文檔,需要的朋友可以參考下2014-10-10C語言靜態(tài)動態(tài)兩版本通訊錄實戰(zhàn)源碼
這篇文章主要為大家?guī)砹薈語言實現(xiàn)靜態(tài)動態(tài)兩版本的通訊錄實戰(zhàn)源碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-02-02