Go 入门 - Linked List

1. Make use of the package container/list to create a(doubly) linked list.Push the values 1,2 and 4 to the list and then print it.

package main

import (
	"container/list"
	"fmt"
)

func main()  {
	l := list.New()
	l.PushBack(1)
	l.PushBack(2)
	l.PushBack(4)
	for e := l.Front(); e!= nil; e = e.Next() {
		fmt.Printf("%v\n", e.Value)
	}
}


2. Create your own linked list implementation.And perform the same actions as in question 1
 

package main

import (
	"errors"
	"fmt"
)

type Value int // Declare a type for the value our list will contain
type Node struct { //Declare a type for the each node in our list
	Value
	prev,next *Node
}

type List struct {
	head, tail *Node
}

//Mimic the interface of container/list
func (l *List) Front() *Node {
	return l.head
}

func (n *Node) Next() *Node {
	return n.next
}

func (l *List) Push(v Value) * List{
	n := &Node{Value:v} //When pushing,create a new Node with the provided value
	if l.head == nil {//If the list is empty.put the new node at the head
		l.head = n
	} else {
		l.tail.next = n //otherwise put it at the tail
		n.prev = l.tail //make sure the new node points back to the previously existing one
	}
	l.tail = n //point tail to the newly inserted node
	return l
}

var errEmpty = errors.New("List is empty")
func (l *List) Pop() (v Value, err error){
	if l.tail == nil {
		err = errEmpty //when popping,return an error if the list is empty
	} else {
		v = l.tail.Value //otherwise save the last value
		l.tail = l.tail.prev //discard the last node from the list
		if l.tail == nil {
			l.head = nil // and make sure the list is consistent if it becomes empty
		}
	}
	return v,err
}

func main()  {
	l := new(List)
	l.Push(1)
	l.Push(2)
	l.Push(4)
	fmt.Println()
	for v, err := l.Pop(); err == nil; v,err=l.Pop() {
		fmt.Printf("%v\n", v)
	}
}

猜你喜欢

转载自blog.csdn.net/zhengwish/article/details/87694462