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
| package main
import "fmt"
const COUNT = 10
type LinkNode struct { No int next *LinkNode }
func InsertNode(head *LinkNode, insertNode *LinkNode) { mark := head for { if head.next == nil { insertNode.next = head head.next = insertNode fmt.Printf("Insert first node %d.\n", head.next.No) return } if head.next.No > insertNode.No { insertNode.next = head.next head.next = insertNode fmt.Printf("Insert node %d in middle.\n", head.next.No) return } if head.next == mark { insertNode.next = head.next head.next = insertNode fmt.Printf("Insert node %d in tail.\n", head.next.No) return } head = head.next } }
func DeleteNode(head *LinkNode, no int) *LinkNode { if no <= 0 { fmt.Printf("Invalid node %d.\n", no) return head } mark := head for { if head.next == mark { if head.next.No == no { head.next = head.next.next fmt.Printf("Delete node %d.\n", no) return head.next } fmt.Printf("Not found node %d.\n", no) return head.next } if head.next.No == no { head.next = head.next.next fmt.Printf("Delete node %d.\n", no) return mark } head = head.next } }
func ListNode(head *LinkNode) { mark := head for { fmt.Printf("List node number: %v\n", head.No) if head.next == mark { fmt.Println("List is empty.") return } head = head.next } }
func main() { linkNodeMap := make(map[int]*LinkNode, COUNT) for i := 1; i <= COUNT; i++ { linkNodeMap[i] = &LinkNode{No: i} } headNode := &LinkNode{} for _, node := range linkNodeMap { InsertNode(headNode, node) } ListNode(headNode) headNode = DeleteNode(headNode, 0) headNode = DeleteNode(headNode, 3) headNode = DeleteNode(headNode, 6) headNode = DeleteNode(headNode, 11) ListNode(headNode) }
|