82. 删除排序链表中的重复元素 II

82. 删除排序链表中的重复元素 II

解法一: 一次遍历

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
p := &ListNode{
Val: -1000,
Next: head,
}
cur := p
for cur != nil {
if cur.Next != nil && cur.Next.Next != nil && cur.Next.Val == cur.Next.Next.Val {
curVal := cur.Next.Val
for cur.Next != nil && curVal == cur.Next.Val {
cur.Next = cur.Next.Next
}
} else {
cur = cur.Next
}
}
return p.Next
}

解法二: 递归

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
if head.Val == head.Next.Val {
next := head.Next
for next != nil && head.Val == next.Val {
next = next.Next
}
return deleteDuplicates(next)
}
head.Next = deleteDuplicates(head.Next)
return head
}
作者

wuhunyu

发布于

2024-01-15

更新于

2024-01-15

许可协议