1. 程式人生 > >[leetcode]82. Remove Duplicates from Sorted List

[leetcode]82. Remove Duplicates from Sorted List

!= pos public gpo tno || 下一個 重復 sort

第一題:遍歷鏈表,遇到重復節點就連接到下一個。

public ListNode deleteDuplicates(ListNode head) {
        if (head==null||head.next==null) return head;
        ListNode res = head;
        while (head.next!=null){
            if (head.val==head.next.val)
            {
                if (head.next.next!=null) head.next = head.next.next;
                
else head.next = null; } else head = head.next; } return res; }

第二題:思路比較簡單,設置一個超前節點作為head的前節點,往下遍歷,遇到重復的就把超前節點連接到新的val節點。

public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode res = new ListNode(0);
        res.next 
= head; ListNode list = res; while (res.next!=null&&res.next.next!=null) { ListNode temp = res.next.next; if (res.next.val==res.next.next.val) { while (temp.next!=null&&temp.next.val==temp.val) { temp
= temp.next; } if (temp.next!=null) res.next = temp.next; else res.next = null; } else res =res.next; } return list.next; }

當要經常刪除第一個節點是,要設置一個超前節點

[leetcode]82. Remove Duplicates from Sorted List