Leetcode_題解_鏈表_NO83_remove-duplicates-from-sorted-list

 

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list

題目

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

給定一個排序鏈表,刪除所有重複的元素,使得每個元素只出現一次。

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

 

解題思路:

通過兩個額外的指針實現

1個指針 combFirst  指向重複的第一個節點 , 另一個指針 index 進行遍歷。

當發現 當前節點(第一個重複點)  與下一個節點重複

  •    則 combFirst 指向 該節點, 並保持不動。
  •    index 繼續向下移動,直到index節點的值和 combFirst的值不一致。
  •    把combFrist 的next 指向 index節點。

當不重複

  •   index向下移動
  •   combFirst 執向indx

 

代碼

package com.offer.test.leetcode;


//Given a sorted linked list, delete all duplicates such that each element appear only once.
//        Example 1:
//        Input: 1->1->2
//        Output: 1->2
//        Example 2:
//        Input: 1->1->2->3->3
//        Output: 1->2->3


class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}


/**
 * Created by szh on 2020/6/2.
 */
public class DelDuplicateElement {


    public static ListNode deleteDuplicates(ListNode head) {

        if (head == null || head.next == null) {
            return head;
        }


        ListNode indexNode = head;
        ListNode combFirst = indexNode;

        while (indexNode != null) {

            if (indexNode.next != null && indexNode.next.val == combFirst.val) {

                combFirst = indexNode;
                indexNode = indexNode.next;

                while (indexNode != null && indexNode.val == combFirst.val) {
                    indexNode = indexNode.next;
                }
                combFirst.next = indexNode;
                combFirst = indexNode;
            } else {

                indexNode = indexNode.next;
                combFirst = indexNode;
            }
        }

        return head;
    }


    public static void main(String[] args) {

        ListNode _1 = new ListNode(1);
        ListNode _2 = new ListNode(1);
        ListNode _3 = new ListNode(2);
        ListNode _4 = new ListNode(2);
        ListNode _5 = new ListNode(3);
        ListNode _6 = new ListNode(3);

        _1.next = _2;
        _2.next = _3;
        _3.next = _4;
        _4.next = _5;
        _5.next = _6;

        ListNode a = deleteDuplicates(_1);
        while (a != null) {
            System.out.println(a.val);
            a = a.next;
        }


    }


}

 

注意:

 if (indexNode.next != null && indexNode.next.val == combFirst.val) 

的反面包含了兩種情況

1.indeNode.next == null

2.indexnode next != null && indexNode.next.val != combFirst.val

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章