day05
# JZ76 删除链表中重复的结点 (opens new window)
# 我的实现
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pHead ListNode类
* @return ListNode类
*/
func deleteDuplication(pHead *ListNode) *ListNode {
if pHead == nil {
return nil
}
next := pHead.Next
cur := pHead
head := &ListNode{0, cur}
prev := head
for next != nil {
if cur.Val == next.Val || cur.Val == head.Val {
head.Val = cur.Val
prev.Next = next
} else {
prev = cur
}
cur = next
next = next.Next
}
if cur.Val == head.Val {
prev.Next = next
}
return head.Next
}
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 官方思路
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pHead ListNode类
* @return ListNode类
*/
func deleteDuplication(pHead *ListNode) *ListNode {
if pHead == nil {
return nil
}
head := &ListNode{0, pHead}
prev := head
cur := prev.Next
next := cur.Next
for next != nil {
if cur.Val == next.Val {
next = next.Next
} else if cur.Val == cur.Next.Val {
cur = next
next = next.Next
prev.Next = cur
} else {
prev = cur
cur = next
next = next.Next
}
}
if cur.Next != nil && cur.Val == cur.Next.Val {
prev.Next = nil
}
return head.Next
}
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# JZ18 删除链表的节点 (opens new window)
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param val int整型
* @return ListNode类
*/
func deleteNode(head *ListNode, val int) *ListNode {
if head == nil {
return nil
}
h := &ListNode{0, head}
prev := h
cur := h.Next
for cur != nil {
cur = cur.Next
if prev.Next.Val == val {
prev.Next = cur
} else {
prev = prev.Next
}
}
return h.Next
}
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
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
上次更新: 2023/07/29, 17:09:37