【LeetCode-面試演算法經典-Java實現】【083-Remove Duplicates from Sorted List(排序的單鏈表中重複資料刪除的結點)】

來源:互聯網
上載者:User

標籤:單鏈表   演算法   面試   java   offer   

【083-Remove Duplicates from Sorted List(排序的單鏈表中重複資料刪除的結點)】 【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】 原題

  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.

題目大意

  給定一個單鏈表,重複資料刪除的元素,相同的只保留一個。

解題思路

  使用一個指標指向鏈表的頭,如果下一個與當前的結點相等則刪除,直到遇到一個不相同的,則指標指向這個新的結點,重複操作,直到所有的結點都處理完。

代碼實現

結點類

public class ListNode {    int val;    ListNode next;    ListNode(int x) {        val = x;        next = null;    }}

演算法實作類別

public class Solution {    public ListNode deleteDuplicates(ListNode head) {        ListNode point;        ListNode tail = head; // 指向新結點的尾部,開始時新鏈只有一個元素,就是鏈頭        if (head != null) {            point = head.next; // 指向另一個鏈的頭部            while ( point != null) { // 另一個鏈還未到末尾                if (tail.val != point.val) { // 如果與尾節點不相同,就將不相同的節點連結到tail的下一個位置                    tail.next = point;                    tail = tail.next; // 重新指向鏈尾                }                point = point.next;            }            tail.next = null; // 鏈尾指向空        }        return head;    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明 歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47270975】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【LeetCode-面試演算法經典-Java實現】【083-Remove Duplicates from Sorted List(排序的單鏈表中重複資料刪除的結點)】

聯繫我們

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