给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路一:
递归的思想,先找到终止条件:链表只剩一个元素。每次递归要做什么:删除一个重复的结点。
代码:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null){ //终止条件
return head;
}
head.next = deleteDuplicates(head.next);//递归调用,每次删除一个重复结点
if(head.val == head.next.val) head = head.next;//如果head和head.next重复,则将head指向head.next(即删除head)
return head;
}
}
思路二:
非递归。链表是有序的,所以每次判断下一位是否和当前位置重复,如果重复则指向下一个结点之后的结点。
代码:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode pre = null;
ListNode node = head;
while(node != null){
if(pre != null && pre.val == node.val)
pre.next = node.next;
else
pre = node;
node = node.next;
}
return head;
}
}
思路三:
双指针法。定义一个指针current,指向当前的结点,另一个指针index指向下一个不重复结点的位置,如果遇到重复结点则不断下移,直到找到不重复的结点位置。
代码:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
if (head == null) return null;
ListNode index = head.next;
while (index != null) {
if (current.val == index.val) {
index = index.next;
} else {
current.next = index;
current = index;
index = index.next;
}
}
current.next = index;
return head;
}
}