问题描述
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
定义两个指针,像上面一样执行,到第四步时,发现重复。则用指针second完成对第二个3节点的删除(second.next=first.next),然后需要把first赋值到second的前面(因为有可能链表中有多个重复)。
测试用例
[]空的
[1,2,3,3]只重复一次的
[1,1,2,2,3,3,4]重复多次的
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return null;
}
//定义两个指针,前面、后面以
ListNode first=head;
ListNode second=first;
first=first.next;
//遍历指针
while(first!=null){
if(first.val==second.val){
second.next=first.next;
first=first.next;
continue;
}
//first和second继续往下遍历
first=first.next;
second=second.next;
}
return head;
}
}
补充
这个题目其实一个指针就可以解决问题了。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return null;
}
//定义两个指针,前面、后面以
ListNode first=head;
//遍历指针
while(first.next!=null){
if(first.val==first.next.val){
first.next=first.next.next;
continue;
}
//first和second继续往下遍历
first=first.next;
}
return head;
}
}