题目:82. 删除排序链表中的重复元素 II
思路:链表,时间复杂度0(n)。
C++版本:
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
//避免处理完后为空的情况
ListNode new_head(0,head);
ListNode *cur=&new_head;
// 每次判断都判断两个连续相邻节点
while(cur->next && cur->next->next){
int val=cur->next->val;
// 相等的话,说明这些相等的都不要
if(cur->next->next->val==val){
// 进入循环,直到下一个节点不和val相等为止
while(cur->next && cur->next->val==val){
cur->next=cur->next->next;
}
}else{
cur=cur->next;
}
}
return new_head.next;
}
};
JAVA版本:
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode new_head=new ListNode(0,head);
ListNode cur=new_head;
while(cur.next!=null && cur.next.next!=null){
int val=cur.next.val;
if(cur.next.next.val==val){
while(cur.next!=null && cur.next.val==val){
cur.next=cur.next.next;
}
}else{
cur=cur.next;
}
}
return new_head.next;
}
}
GO版本:
go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
new_head:=&ListNode{Val:0,Next:head}
cur:=new_head
for cur.Next!=nil && cur.Next.Next!=nil {
val:=cur.Next.Val
if cur.Next.Next.Val==val {
for cur.Next!=nil && cur.Next.Val==val {
cur.Next=cur.Next.Next
}
}else{
cur=cur.Next
}
}
return new_head.Next
}