|
| 1 | +package linkedlist |
| 2 | + |
| 3 | +import "fmt" |
| 4 | + |
| 5 | +type ListNode struct { |
| 6 | + val interface{} |
| 7 | + pre *ListNode |
| 8 | + next *ListNode |
| 9 | +} |
| 10 | + |
| 11 | +func NewIntList(nums []int) *ListNode { |
| 12 | + if len(nums) == 0 { |
| 13 | + return nil |
| 14 | + } |
| 15 | + dummy := &ListNode{} |
| 16 | + head := dummy |
| 17 | + for _, val := range nums { |
| 18 | + node := &ListNode{ |
| 19 | + val: val, |
| 20 | + } |
| 21 | + node.pre = head |
| 22 | + head.next = node |
| 23 | + head = node |
| 24 | + } |
| 25 | + |
| 26 | + return dummy.next |
| 27 | +} |
| 28 | + |
| 29 | +func (head *ListNode) Print() { |
| 30 | + curr := head |
| 31 | + for curr != nil { |
| 32 | + fmt.Printf("%v, ", curr.val) |
| 33 | + curr = curr.next |
| 34 | + } |
| 35 | + println() |
| 36 | +} |
| 37 | + |
| 38 | +func (head *ListNode) String() string { |
| 39 | + s := "" |
| 40 | + curr := head |
| 41 | + for curr != nil { |
| 42 | + s += fmt.Sprintf("%v, ", curr.val) |
| 43 | + curr = curr.next |
| 44 | + } |
| 45 | + return s |
| 46 | +} |
| 47 | + |
| 48 | +// 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 |
| 49 | +func DeleteDuplicates(head *ListNode) *ListNode { |
| 50 | + current := head |
| 51 | + for current != nil { |
| 52 | + for current.next != nil && current.next.val == current.val { |
| 53 | + current.next = current.next.next |
| 54 | + } |
| 55 | + current = current.next |
| 56 | + } |
| 57 | + |
| 58 | + return head |
| 59 | +} |
| 60 | + |
| 61 | +// 给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现的数字。 |
| 62 | +// 只出现一次的节点 |
| 63 | +func DeleteDupKeepOnce(head *ListNode) *ListNode { |
| 64 | + dummy := &ListNode{} |
| 65 | + dummy.next = head |
| 66 | + current := dummy |
| 67 | + |
| 68 | + var rmVal interface{} |
| 69 | + for current.next != nil && current.next.next != nil { |
| 70 | + if current.next.val == current.next.next.val { |
| 71 | + rmVal = current.next.val |
| 72 | + // 指针直接跳到第三个节点 |
| 73 | + current.next = current.next.next.next |
| 74 | + // 顺序删除 |
| 75 | + for current.next != nil && current.next.val == rmVal { |
| 76 | + current.next = current.next.next |
| 77 | + } |
| 78 | + } else { |
| 79 | + current = current.next |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + return dummy.next |
| 84 | +} |
| 85 | + |
| 86 | +// 反转一个单链表。 |
| 87 | +// 思路:用一个 prev 节点保存向前指针,temp 保存向后的临时指针 |
| 88 | +func ReverseList(head *ListNode) *ListNode { |
| 89 | + var pre *ListNode |
| 90 | + for head != nil { |
| 91 | + temp := head.next |
| 92 | + head.next = pre |
| 93 | + pre = head |
| 94 | + head = temp |
| 95 | + } |
| 96 | + |
| 97 | + return pre |
| 98 | +} |
0 commit comments