Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6. // create list
  7. l := new(List)
  8. // append to list
  9. for i := 0; i < 100; i++ {
  10. l.Append(i)
  11. }
  12.  
  13. // print everything in the list
  14. for node := l.GetRoot(); node != nil; node = node.Next() {
  15. fmt.Println(node.Value())
  16. }
  17.  
  18. fmt.Println(">>>>>>>>>>>>>>")
  19.  
  20. // reverse the list
  21. l2 := l.Reverse()
  22.  
  23. // print everything in the list
  24. for node := l2.GetRoot(); node != nil; node = node.Next() {
  25. fmt.Println(node.Value())
  26. }
  27. }
  28.  
  29. // Node - node structure in linked list
  30. type Node struct {
  31. next *Node
  32. value interface{}
  33. }
  34.  
  35. // Next - helper to get the next value
  36. func (n *Node) Next() *Node {
  37. return n.next
  38. }
  39.  
  40. // Value - helper to get the node value
  41. func (n *Node) Value() interface{} {
  42. return n.value
  43. }
  44.  
  45. // List - linked list implementation
  46. type List struct {
  47. root *Node
  48. }
  49.  
  50. // Append - append a value to the list
  51. func (l *List) Append(v interface{}) {
  52. // if the root is nil, make the root of the list contain this value
  53. if l.root == nil {
  54. l.root = &Node{
  55. value: v,
  56. }
  57. return
  58. } else {
  59. // otherwise keep recursing
  60. listAppend(l.GetRoot(), v)
  61. }
  62. }
  63.  
  64. // listAppend - recursively append a node to a list
  65. func listAppend(node *Node, v interface{}) {
  66. // if we are at the end of the list, make the next
  67. // node a new one containing value v as value
  68. if node.Next() == nil {
  69. node.next = &Node{
  70. value: v,
  71. }
  72. } else {
  73. // we are not at the end yet, keep recursing.
  74. listAppend(node.Next(), v)
  75. }
  76. }
  77.  
  78. // GetRoot - helper to get the root node of a list
  79. func (l *List) GetRoot() *Node {
  80. return l.root
  81. }
  82.  
  83. // Reverse - List reversal produces a list in the reverse
  84. func (l *List) Reverse() *List {
  85. newList := new(List)
  86. // call recursive reversal
  87. listReverse(l.root, newList)
  88. return newList
  89. }
  90.  
  91. // listReverse - recursive list reversal
  92. func listReverse(node *Node, newList *List) {
  93. // if we are not at the end of the list, keep recursing
  94. if node.Next() != nil {
  95. listReverse(node.Next(), newList)
  96. }
  97. // append a node to the new list
  98. newList.Append(node.Value())
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement