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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| package main
import "fmt"
type LanNode struct { No int Name string next *LanNode pre *LanNode }
func newNode(no int, name string) *LanNode{ return &LanNode{ No:no, Name:name, } }
func insertNode(head *LanNode, newNode *LanNode) { tmp := head for { if tmp.next == nil { tmp.next = newNode fmt.Println("已经遍历到链表尾部,插入成功") return } if tmp.next.No > newNode.No { newNode.next = tmp.next newNode.pre = tmp tmp.next.pre = newNode tmp.next = newNode
fmt.Println("已经插入到合适位置") return }
if tmp.next.No == newNode.No { fmt.Println("无法插入该节点,已有相同No") return } tmp = tmp.next } }
func deleteNode(head *LanNode, no int) { tmp := head for { if tmp.next == nil { fmt.Println("不存在待删除的no") return } if tmp.next.No == no { tmp.next = tmp.next.next if tmp.next != nil { tmp.next.pre = tmp } fmt.Println("删除成功") return } tmp = tmp.next }
}
func listNode(head *LanNode) { for { if head.next == nil { fmt.Println("已经遍历到底部") return } else { fmt.Printf("No为%d, Name为%s语言 ==> ",head.next.No, head.next.Name) } head = head.next } }
func main() { headNode := &LanNode{}
nodeC := newNode(1, "C") nodePHP := newNode(2, "PHP") nodeJava := newNode(3, "Java") nodeNodeJs := newNode(4, "NodeJs")
insertNode(headNode, nodeC) insertNode(headNode, nodeJava) insertNode(headNode, nodeNodeJs) insertNode(headNode, nodePHP)
listNode(headNode)
deleteNode(headNode, 3) listNode(headNode)
}
|