Leetcode: Remove Duplicates from Sorted List

时间:2021-06-22 07:35:52
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.

遇到的问题:input{1,1,1}, output{1,1}, expected{1}, 原因在于若temp.val==temp.next.val, 则需要temp.next=temp.next.next, 这时候就不要temp=temp.next了

注意停止条件不是temp!=null,而是temp.next!=null

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode deleteDuplicates(ListNode head) {
14         if(head==null) return null;
15         ListNode temp=head;
16         while(temp.next!=null){
17             if(temp.val==temp.next.val){
18                 temp.next=temp.next.next;
19             }
20             else temp=temp.next;
21         }
22         return head;
23     }
24 }

维护两个指针,一个指向当前不重复的最后一个元素,一个进行依次扫描,遇到不重复的则更新第一个指针,继续扫描,否则就把前面指针指向当前元素的下一个(即把当前元素从链表中删除)。时间上只需要一次扫描,所以是O(n),空间上两个额外指针,是O(1)。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode deleteDuplicates(ListNode head) {
14         if (head == null || head.next == null) return head;
15         ListNode walker = head;
16         ListNode runner = head.next;
17         while (walker != null && runner != null) {
18             if (walker.val == runner.val) {
19                 walker.next = runner.next;
20                 runner = runner.next;
21             }
22             else {
23                 walker = walker.next;
24                 runner = runner.next;
25             }
26         }
27         return head;
28     }
29 }