implement stack using linked list in golang

Go program for implement stack using linked list. Here more information.

package main
import "fmt"
// Go program for
// Implementation stack using linked list

// Stack Node
type StackNode struct {
	data int
	next * StackNode
}
func getStackNode(data int, top * StackNode) * StackNode {
	// return new StackNode
	return &StackNode {
		data,
		top,
	}
}
type MyStack struct {
	top * StackNode
	count int
}
func getMyStack() * MyStack {
	// return new MyStack
	return &MyStack {
		nil,
		0,
	}
}
// Returns the number of element in stack
func(this MyStack) size() int {
	return this.count
}
func(this MyStack) isEmpty() bool {
	if this.size() > 0 {
		return false
	} else {
		return true
	}
}
// Add a new element in stack
func(this *MyStack) push(data int) {
	// Make a new stack node
	// And set as top
	this.top = getStackNode(data, this.top)
	// Increase node value
	this.count++
}
// Add a top element in stack
func(this *MyStack) pop() int {
	var temp int = 0
	if this.isEmpty() == false {
		// Get remove top value
		temp = this.top.data
		this.top = this.top.next
		// Reduce size
		this.count--
	}
	return temp
}
// Used to get top element of stack
func(this MyStack) peek() int {
	if !this.isEmpty() {
		return this.top.data
	} else {
		return 0
	}
}

func main() {
	// Create new stack 
	var s * MyStack = getMyStack()
	fmt.Println("\n Is empty : ", s.isEmpty())
	// Add element
	s.push(15)
	s.push(14)
	s.push(31)
	s.push(21)
	s.push(10)
	fmt.Println("\n Top  : ", s.peek())
	fmt.Println(" Size : ", s.size())
	fmt.Println("\n Is empty : ", s.isEmpty())
	// Delete Stack Element
	var data int = s.pop()
	fmt.Println("\n Pop element ", data)
	fmt.Println(" Size : ", s.size())
	data = s.pop()
	fmt.Println("\n Pop element ", data)
	fmt.Println(" Size : ", s.size())
}

Output

 Is empty :  true

 Top  :  10
 Size :  5

 Is empty :  false

 Pop element  10
 Size :  4

 Pop element  21
 Size :  3


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved