leetcode:Remove Nth Node From End of List(刪除連結串列倒數第n個節點)【面試演算法題】
阿新 • • 發佈:2019-02-17
題目:
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.
由於連結串列是單向的,不能倒著搜尋,因此設定兩個指標,他們相隔n個節點的距離,同布移動。
當前面的指標到達連結串列結尾的時候,後面一個指標離結尾的距離正好是n,再刪除要求的節點就ok了。
要注意的我覺得應該有兩點:
第一如果連結串列不到n個節點,就沒有刪除的元素,判斷一下防止非法訪問記憶體(後來發現題目說了沒有這個情況,隨意了就當作程式碼嚴謹一點吧)。
第二不好刪除當前訪問的節點,特別是刪除的頭節點就比較麻煩了。所以增加一個節點連結頭節點,這樣間隔距離多一步,就能容易地刪除下一個節點了。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { ListNode *left,*right,*Head; right=head; for(int i=0;i<n;++i) { if(!right)return head; right=right->next; } Head=left=new ListNode(-1); Head->next=head; while(right) { right=right->next; left=left->next; } ListNode *t1=left->next,*t2; if(t1)left->next=left->next->next; delete(t1); t2=Head->next; delete(Head); return t2; } }; // blog.csdn.net/havenoidea
題解目錄