链表——实现队列和栈

package linkedTabl

import (
	"fmt"
	"testing"
)

type node struct {
	Val int
	Last *node
	Next *node
}

type DoubleEndsQueue struct {
	Head *node
	Tail *node
}

func (d *DoubleEndsQueue) addFromHead(value int)  {
	cur := &node{Val: value}
	if d.Head == nil {
		d.Head = cur
		d.Tail = cur
	}else {
		cur.Next = d.Head
		d.Head.Last = cur
		d.Head = cur
	}
}


func (d *DoubleEndsQueue)popFromHead()  int {
	if d.Head == nil {
		return -1
	}
	cur := d.Head
	if d.Head == d.Tail {
		d.Head = nil
		d.Tail = nil
	}else {
		d.Head = d.Head.Next
		cur.Next = nil
		d.Head.Last = nil
	}
	return cur.Val
}

func (d *DoubleEndsQueue) addFromBottom(value int)  {
	cur := &node{Val: value}
	if d.Head == nil {
		d.Head = cur
		d.Tail = cur
	}else {
		cur.Last = d.Tail
		d.Tail.Next = cur
		d.Tail = cur
	}
}


func (d *DoubleEndsQueue)popFromBottom() int {
	if d.Head == nil {
		return -1
	}

	cur := d.Tail
	if d.Head == d.Tail {
		d.Head = nil
		d.Tail = nil
	}else {
		d.Tail = d.Tail.Last
		d.Tail.Next = nil
		cur.Last = nil
	}
	return cur.Val
}

func (d *DoubleEndsQueue)isEmpty() bool {
	return d.Head == nil
}


type MyStack struct {
	Queue *DoubleEndsQueue
}

func NewMyStack() *MyStack {
	return &MyStack{
		Queue: &DoubleEndsQueue{
			Head: nil,
			Tail: nil,
		},
	}
}


func (s *MyStack) Push(val int) {
	s.Queue.addFromHead(val)
}

func (s *MyStack) Pop() int {
	return s.Queue.popFromHead()
}

func (s *MyStack) isEmpty() bool {
	return s.Queue.isEmpty()
}

type MyQueue struct {
	Queue *DoubleEndsQueue
}

func NewMyQueue() *MyQueue {
	return &MyQueue{
		Queue: &DoubleEndsQueue{
			Head: nil,
			Tail: nil,
		},
	}
}


func (s *MyQueue) Push(val int) {
	s.Queue.addFromHead(val)
}

func (s *MyQueue) Poll() int {
	return s.Queue.popFromBottom()
}

func (s *MyQueue) isEmpty() bool {
	return s.Queue.isEmpty()
}

func TestMyStack(t *testing.T)  {
	stack := NewMyStack()
	stack.Push(1)
	stack.Push(100)
	stack.Push(567)
	stack.Queue.addFromBottom(999)

	fmt.Println(stack.Pop())
	fmt.Println(stack.Pop())
	fmt.Println(stack.Pop())
	fmt.Println(stack.isEmpty())
	fmt.Println(stack.Pop())
}


func TestMyQueue(t *testing.T)  {
	queue := NewMyQueue()
	queue.Push(1)
	queue.Push(100)
	queue.Push(567)
	queue.Push(597)
	queue.Queue.addFromBottom(999)


	fmt.Println(queue.Poll())
	fmt.Println(queue.Poll())
	fmt.Println(queue.Poll())
	fmt.Println(queue.isEmpty())
	fmt.Println(queue.Poll())
	fmt.Println(queue.Poll())

}
上一篇:linux文件操作命令--查看、编辑


下一篇:Linux 常用基础命令