Remove Duplicates from Sorted List,duplicatessorted

來源:互聯網
上載者:User

Remove Duplicates from Sorted List,duplicatessorted

本文是在學習中的總結,歡迎轉載但請註明出處:http://blog.csdn.net/pistolove/article/details/41728739


Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

思路:

(1)題意為移除已排序鏈表中重複元素。

(2)首先,對頭結點進行判空,為空白則返回空。不為空白設定first指向head。

(3)其次,判斷first的後續節點second是否為空白,如果不為空白,則比較它們值是否相同。如果值不同,則節點first指向second,

         second指向first的後續節點,迴圈繼續;如果值相同,設定節點last指向second的後續節點,如果last不為空白,並且last的值

         和first的值相同(說明連續三個節點值相同),last指向其後續節點,迴圈直到ast為空白或者first的值和last的值不同,此時,

         如果last不為空白,則first的後續節點為last,first指向last,second指向first的後續位置,迴圈繼續,如果last為空白,說明已經

         遍曆到最後節點,此first的後續節點指向null,返回head。

(4)其指向過程可以簡單如下所示:
         例如:1->1->2->3->3->3->4->5->5->5
                  (A)first=1,second=1,first=second,則last=2,由於first!=last,所以first=2,second=3;
                  (B)first=2,second=3,first!=second,則first=3,second=3;
                  (C)first=3,second=3,first=second,則last=3,由於first=last,迴圈直到last==null或者first!=last,此時last=4,則first=4,second=5;
                  (D)first=4,second=5,first!=second,則first=5,last=5;
                  (E)first=5,last=5,first=second,last=5,由於first=last,迴圈直到last==null或者first!=last,此時last=null,則first.next=null,返回head。


演算法代碼實現如下:

public ListNode deleteDuplicates(ListNode head) {    if (head == null)return null;ListNode first = head;ListNode second = first.next;while (second != null) {if (first.val == second.val) {ListNode last = second.next;while (last != null && first.val == last.val) {last = last.next;}if (last != null) {first.next = last;first = last;second = first.next;} else {first.next=null;return head;}} else {first = second;second = first.next;}}return head;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.