注意鏈表的尾部

來源:互聯網
上載者:User

標籤:style   blog   color   for   io   代碼   

今天做了Leetcode上面一道題Remove Duplicates from Sorted List II,要去去除鏈表中重複的節點,代碼如下

 1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     ListNode *deleteDuplicates(ListNode *head) {12         if(head==NULL||head->next==NULL)13         {14             return head;15         }16         ListNode *p=head,*prev=new ListNode(0),*head2=prev;17         int count=0;18         while(p->next!=NULL)19         {20             if(count==0&&p->val!=p->next->val)21             {22                 prev->next=p;23                 prev=p;24             }25             else if(p->val==p->next->val)26             {27                 count++;28             }29             else if(count>0)30             {31                 count=0; 32             }33             p=p->next;34         }35         if(count==0)36         {37             prev->next=p;38         }39        // else40        //{41        //     prev->next=NULL;42        //}43         head=head2->next;44         delete head2;45         return head;46     }47 };

注意到39-42行被注釋掉的代碼,注釋掉,會怎麼樣?

分析一下演算法,count表示前面與當前指標val相等的節點個數,對於末尾指標,前面如果沒有與其數值相等,則加入鏈表,否則,則不加入鏈表,但是,如果末尾指標前面存在與其相等的數,是不是可以不用管它?不是的,因為是原地對鏈表操作,所以如果不處理的畫,那麼最後prev的next還是會指向另一個節點,而這個節點並不是我們想要的,所以39-42行必須將prev的next指向null 指標。當然對於存在重複的節點,可以直接delete之,如果該節點是分配到堆上的話。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.