daily pastebin goal
77%
SHARE
TWEET

Untitled

a guest Jan 16th, 2018 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6.   list := List{}
  7.   list.insert(2)
  8.   list.insert(4)
  9.   list.insert(6)
  10.   list.printListInfo()
  11. }
  12.  
  13. // Node Type
  14. type Node struct {
  15.   data int
  16.   next *Node
  17. }
  18.  
  19. // LinkedList Type
  20. type List struct {
  21.   head *Node
  22. }
  23.  
  24. func (self *List) printListInfo() {
  25.   fmt.Println("\nList Info:")
  26.   fmt.Printf("items: %v\n", self.items())
  27.   fmt.Printf("count: %v\n", self.count())
  28.   fmt.Println("\n")
  29. }
  30.  
  31. func (l *List) insert(n int) {
  32.   if l.head == nil {
  33.     l.head = &Node{ n, l.head }
  34.   } else {
  35.     temp := l.head
  36.     last := l.head
  37.  
  38.     for temp != nil {
  39.       last = temp
  40.       temp = temp.next
  41.     }
  42.     last.next = &Node { n, nil }
  43.   }
  44.  
  45.   l.printNodes()
  46. }
  47.  
  48. func (l *List) printNodes() {
  49.   temp := l.head
  50.   for temp != nil {
  51.     fmt.Printf("%v ", temp.data)
  52.     temp = temp.next
  53.   }
  54.   fmt.Println()
  55. }
  56.  
  57. func (l *List) count() int {
  58.   temp := l.head
  59.   count := 0
  60.   for temp != nil {
  61.     count += 1
  62.     temp = temp.next
  63.   }
  64.   return count
  65. }
  66.  
  67. func (l *List) items() []int {
  68.   temp := l.head
  69.  
  70.   var nodes []int
  71.  
  72.   for temp != nil {
  73.     nodes = append(nodes, temp.data)
  74.     temp = temp.next
  75.   }
  76.   return nodes
  77. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top