Leetcode: Remove Duplicates from Sorted List

本文介绍了一种算法,该算法可以删除已排序链表中的所有重复元素,确保每个元素仅出现一次。通过维护两个指针,一个指向当前不重复的最后一个元素,另一个进行扫描。遇到重复元素时,将其跳过;反之,则更新第一个指针。
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 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/3704782.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值