刪除連結串列的倒數第n個結點
阿新 • • 發佈:2018-11-20
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
題意:刪除連結串列的倒數第n個結點,並返回連結串列的頭指標 思路一:將倒數第n個轉換成正數第(連結串列長度-n+1)個class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { //刪除倒數第n個轉化為,刪除正數第幾個 //要考慮比較多的特殊情況,head==NULL head->next==NULL//還有len-n==0的 int len1=len(head); if(head==NULL ||head->next==NULL) return NULL; ListNode *p; p=head; if(len1-n==0) head=head->next; else{ for(int i=1;i<len1-n;i++){ p=p->next; } p->next=p->next->next; }return head; } int len(ListNode *Head) { int count=0; while(Head!=NULL){ Head=Head->next; count++; } return count; } };
思路二:設定兩個指標,一個先走n步,然後兩個指標再一起走,等第一個指標到達連結串列最後一個結點,另一個指標指向結點的下一個結點,就是需要刪除的倒數第n個結點
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *p1,*p2; p1=head; p2=head; if(head==NULL || head->next==NULL) return NULL; while(n--){ p1=p1->next; } if(p1==NULL) return head->next; //這種情況直接return,不要只是修改head,這樣後面繼續執行會出錯 while(p1->next!=NULL){ p1=p1->next; p2=p2->next; } p2->next=p2->next->next; return head; } };