双向链表
双向链表的插入和遍历输出
package mainimport ("fmt""math/rand""time"
)type Node struct {Data intPrePoint *NodeNextPont *Node
}type LinkList struct {head *Nodecurrent *Nodetail *Node
}func main() {rand.New(rand.NewSource(time.Now().UnixNano()))datas := make([]int, 10)for i := range 10 {datas[i] = rand.Intn(100)}fmt.Println(datas)linklists := new(LinkList)for _, v := range datas {node := new(Node)node.Data = vlinklists.Insert(node)}linklists.ShowLinkList()
}
func (l *LinkList) Insert(node *Node) {if l.head == nil {l.head = nodel.current = nodel.tail = node} else {l.tail.NextPont = nodenode.PrePoint = l.taill.tail = node // 只移动尾,头指针一直不动,中间的指针也一直不动}
}func (l *LinkList) ShowLinkList() {for c := l.head; c != nil; c = c.NextPont {fmt.Println(c.Data)}
}
合并两个递增链表
package mainimport ("fmt""math/rand""time"
)type Node struct {Data intPrePoint *NodeNextPont *Node
}type LinkList struct {head *Nodecurrent *Nodetail *Node
}func main() {rand.New(rand.NewSource(time.Now().UnixNano()))l1, l2 := new(LinkList), new(LinkList)n1, n2 := 0, 0for range 10 {n1 += rand.Intn(10)n2 += rand.Intn(10)l1.Insert(&Node{Data: n1})l2.Insert(&Node{Data: n2})}l1.ShowLinkList()l2.ShowLinkList()fmt.Println("===================================")m := merge(l1, l2)m.ShowLinkList()}
func (l *LinkList) Insert(node *Node) {if l.head == nil {l.head = nodel.current = nodel.tail = node} else {l.tail.NextPont = nodenode.PrePoint = l.taill.tail = node // 只移动尾,头指针一直不动,中间的指针也一直不动}
}func (l *LinkList) ShowLinkList() {values := make([]int, 0)for c := l.head; c != nil; c = c.NextPont {values = append(values, c.Data)}fmt.Println(values)
}
func merge(l1, l2 *LinkList) (m *LinkList) {m = new(LinkList)c1, c2 := l1.head, l2.headfor c1 != nil && c2 != nil {// 这里是合并递增链表,所以排小的在前面if c1.Data < c2.Data {m.Insert(&Node{Data: c1.Data})c1 = c1.NextPont} else {m.Insert(&Node{Data: c2.Data})c2 = c2.NextPont}}for c1 != nil {m.Insert(&Node{Data: c1.Data})c1 = c1.NextPont}for c2 != nil {m.Insert(&Node{Data: c2.Data})c2 = c2.NextPont}return m
}