🌝

Leetcode203:删除链表节点

Posted at — Jan 06, 2022

 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func create(e int) *ListNode {
	return &ListNode{
		Val:  e,
		Next: nil,
	}
}

func (ln *ListNode) add(e int) *ListNode {
	newNode := ListNode{
		Val:  e,
		Next: nil,
	}

	tmp := ln

	for tmp.Next != nil {
		tmp = tmp.Next
	}

	tmp.Next = &newNode
	return ln
}

func (ln *ListNode) display() {
	tmp := ln
	fmt.Print("ListNodes:")
	for tmp != nil {
		fmt.Printf(" %d", tmp.Val)
		tmp = tmp.Next
	}
	fmt.Println()
}

func removeElements(head *ListNode, val int) *ListNode {
	// copy the head
	s := head
	// pre node
	pre := s
	// current node index of ListNode
	c := 0
	for s != nil {
		if s.Val == val {
			// when the delete target node is head
			if c == 0 {
				head = head.Next
				s = head
				pre = s
				c--
			} else {
			// when the delete target node is not head
				pre.Next = s.Next    // delete the target node
				s = s.Next    // move to next node
			}
		} else {
			// move the pointer to next node
			pre = s
			s = s.Next
		}
		c++
	}
	return head
}

func main() {
	s := create(7).add(7).add(7).add(7).add(7)
	// s := create(1)
	s = removeElements(s, 7)
	s.display()
}

source code