【Leetcode】Remove Duplicates from Sorted List in JAVA

來源:互聯網
上載者:User

標籤:

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.

思路非常easy。因為乖乖的sort好了,就是推斷下一個是不是比它大就好了,假設大,那麼跳過下一個直接link到下一個的下一個。可是此時注意。考慮假設是1->1->1這樣的情況。當你把第二個1刪掉之後。指標一定要保留在第一個的位置,這樣才幹夠接著推斷這個1與再下一個1是不是相等(即第一個1和第3個1)。

唯一須要格外注意的情況就是最後兩個,因為你要p.next=p.next.next來刪除,所以對於最後兩個不存在next的next。所以直接等於null就好啦

package testAndfun;public class deleteDuplicates {public static void main(String args[]){deleteDuplicates dp = new deleteDuplicates();ListNode head  = new ListNode(3);ListNode p1 = new ListNode(3);head.next=p1;ListNode p2  = new ListNode(3);p1.next =  p2;ListNode p3 = new ListNode(3);p2.next = p3;ListNode p4 = new ListNode(13);p3.next = p4;prinf(head);prinf(dp.deleteDup(head));}private static void prinf(ListNode input){while(input!=null){System.out.print(input.val+"->");input = input.next;}System.out.println();}public ListNode deleteDup(ListNode head){if(head==null||head.next==null)return head;//if no head, what should I do?ListNode p=head;int i=0;//System.out.println(p.val+" and "+p.next.val);while(p.next != null){if(p.val==p.next.val&&p.next.next!=null){//System.out.println("go first"+p.val);//"^^"+p.next.val+"%%"+p.next.next.val);p.next=p.next.next;continue;//if this and next equal, we should stay in this in case next.next is equal this}else if(p.val==p.next.val&&p.next.next==null){//System.out.println("go second"+p.val);p.next=null;continue;}//System.out.println(p.val+" round "+i++);p=p.next;if(p==null)break;}//System.out.print(head.val);return head;}}


著作權聲明:本文博主原創文章,部落格,未經同意不得轉載。

【Leetcode】Remove Duplicates from Sorted List in JAVA

聯繫我們

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