Pointers let nodes link to each other to make a list.
What to build
A program that implements a stack with a linked list and runs commands on it.
Requirements
- Read n, then n commands:
push X,pop,print,reverseorsize. pushputs X on top.popremoves the top and prints it, or printsemptyif the stack has no items.printprints the items from the top to the bottom on one line separated by spaces, orempty.reverseturns the stack upside down.sizeprints the number of items.
Input
Line 1: n. Then n commands.
Output
Messages as described.
Constraints
1 ≤ n ≤ 100; X is between -1000 and 1000.
Example
Input:
7
push 1
push 2
push 3
print
pop
size
print
Output:
3 2 1
3
2
2 1
Why it works
Each node holds a value and a pointer to the node below it. push makes a new node that points at the old top. reverse changes every Next pointer to point backwards, with no new nodes needed.
Examples
Example 1 · Input
7 push 1 push 2 push 3 print pop size print
Expected output
3 2 1 3 2 2 1
Example 2 · Input
3 pop print size
Expected output
empty empty 0
Hints
Hint 1
type Node struct { Val int; Next *Node } and type Stack struct { head *Node; size int }.
Hint 2
Reverse by walking the list and pointing every node's Next at the previous node.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
type Node struct {
Val int
Next *Node
}
type Stack struct {
head *Node
size int
}
func (s *Stack) Push(x int) {
s.head = &Node{Val: x, Next: s.head}
s.size++
}
func (s *Stack) Pop() {
if s.head == nil {
fmt.Println("empty")
return
}
fmt.Println(s.head.Val)
s.head = s.head.Next
s.size--
}
func (s *Stack) Print() {
if s.head == nil {
fmt.Println("empty")
return
}
for cur := s.head; cur != nil; cur = cur.Next {
fmt.Print(cur.Val)
if cur.Next != nil {
fmt.Print(" ")
}
}
fmt.Println()
}
func (s *Stack) Reverse() {
var prev *Node
cur := s.head
for cur != nil {
next := cur.Next
cur.Next = prev
prev = cur
cur = next
}
s.head = prev
}
func main() {
var n int
fmt.Scan(&n)
s := &Stack{}
for i := 0; i < n; i++ {
var cmd string
fmt.Scan(&cmd)
switch cmd {
case "push":
var x int
fmt.Scan(&x)
s.Push(x)
case "pop":
s.Pop()
case "print":
s.Print()
case "reverse":
s.Reverse()
case "size":
fmt.Println(s.size)
}
}
}