type listnode struct { next *listnode value int }
func removenodenormal(head *listnode, value int) *listnode { var prev *listnode for cur := head; cur != nil; cur = cur.next { if cur.value == value { if prev != nil { prev.next = cur.next } else { head = cur.next } } else { prev = cur } } return head }
if 是 || !不是 { 请继续往下看 }
func removenodereplace(head *listnode, value int) *listnode { cur := head for cur != nil && cur.value == value { if cur.next == nil { return nil } cur.value = cur.next.value cur.next = cur.next.next } for cur != nil { if cur.next != nil && cur.next.value == value { cur.next = cur.next.next } else { cur = cur.next } } return head }
func removenode(head *listnode, value int) *listnode { for cur := &head; *cur != nil; { if (*cur).value == value { *cur = (*cur).next } else { cur = &(*cur).next } } return head }
package main import ( "fmt" ) type listnode struct { next *listnode value int } func removenodenormal(head *listnode, value int) *listnode { var prev *listnode for cur := head; cur != nil; cur = cur.next { if cur.value == value { if prev != nil { prev.next = cur.next } else { head = cur.next } } else { prev = cur } } return head } func removenodereplace(head *listnode, value int) *listnode { cur := head for cur != nil && cur.value == value { if cur.next == nil { return nil } cur.value = cur.next.value cur.next = cur.next.next } for cur != nil { if cur.next != nil && cur.next.value == value { cur.next = cur.next.next } else { cur = cur.next } } return head } func removenode(head *listnode, value int) *listnode { for cur := &head; *cur != nil; { if (*cur).value == value { *cur = (*cur).next } else { cur = &(*cur).next } } return head } func arraytolink(nums []int) *listnode { if len(nums) == 0 { return nil } head := &listnode{ value: nums[0], } tail := head for i := 1; i < len(nums); i++ { tail.next = &listnode{ value: nums[i], } tail = tail.next } return head } func linktoarray(head *listnode) []int { var array []int for ; head != nil; head = head.next { array = append(array, head.value) } return array } func arrayequal(nums1, nums2 []int) bool { if len(nums1) != len(nums2) { return false } for i := 0; i < len(nums1); i++ { if nums1[i] != nums2[i] { return false } } return true } func main() { tests := []struct { nums []int value int res []int }{ { []int{}, 1, []int{}, }, { []int{1}, 1, []int{}, }, { []int{1, 2}, 1, []int{2}, }, { []int{1, 2}, 2, []int{1}, }, { []int{1, 2, 1, 3, 1, 4, 1, 1, 1, 1, 1}, 1, []int{2, 3, 4}, }, { []int{1, 2, 3, 2, 4, 2}, 2, []int{1, 3, 4}, }, { []int{3, 1, 3, 2, 3, 4, 3}, 3, []int{1, 2, 4}, }, { []int{4, 1, 4, 2, 4, 3, 4, 4, 4, 4, 4}, 4, []int{1, 2, 3}, }, } for _, test := range tests { head := arraytolink(test.nums) head = removenode(head, test.value) array := linktoarray(head) fmt.println(arrayequal(array, test.res)) } }
如果你对算法感兴趣,可以看看我刷的leetcode: (求赞)
如果你对算法感兴趣,可以看看我刷的leetcode: (求赞)
如果你对算法感兴趣,可以看看我刷的leetcode: (求赞)
如对本文有疑问, 点击进行留言回复!!
VSCode1.4 搭建Golang的开发调试环境(遇到很多问题)
网友评论