Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. package linkedlist
  2.  
  3. type LinkedListValue struct {
  4. next *LinkedListValue
  5. value int
  6. }
  7.  
  8. type LinkedList struct {
  9. head *LinkedListValue
  10. tail *LinkedListValue
  11. length int
  12. }
  13.  
  14. // Append method
  15. func (l *LinkedList) append(value int){
  16. // Create value holder
  17. val := SetupLinkedListValue(value)
  18. // Set tail next to new val
  19. l.tail.next = &val
  20. // Increase list length
  21. l.length++
  22. // Set new tail
  23. l.tail = &val
  24. }
  25.  
  26. // Prepend method
  27. func (l *LinkedList) prepend(value int){
  28. val := SetupLinkedListValue(value)
  29. val.next = l.head
  30. l.length++
  31. l.head = &val
  32. l.cursor = &val
  33. }
  34.  
  35. func (l *LinkedList) traverseToIndex(index int) (val *LinkedListValue){
  36. next := l.head
  37. for i:=0; i<index+1; i++ {
  38. val = next
  39. next = next.next
  40. }
  41. return val
  42. }
  43.  
  44. // Get method. Will get out values with cursor
  45. func (l *LinkedList) get(index int) int{
  46. return l.traverseToIndex(index).value
  47. }
  48.  
  49. func (l *LinkedList) insert(index int, value int){
  50. // Edge case check if head or tail
  51. if index<=0{
  52. l.prepend(value)
  53. return
  54. }else if index>=l.length-1{
  55. l.append(value)
  56. return
  57. }
  58. first:= l.traverseToIndex(index-1)
  59. middle:= SetupLinkedListValue(value)
  60. last:= first.next
  61.  
  62. first.next = &middle
  63. middle.next = last
  64.  
  65. l.length++
  66. }
  67.  
  68. func SetupLinkedListValue(value int) LinkedListValue {
  69. v := LinkedListValue{}
  70. v.value = value
  71. return v
  72. }
  73.  
  74. // Linked list initializer
  75. func NewLinkedList(startVal int) LinkedList {
  76. a := LinkedList{}
  77. first := SetupLinkedListValue(startVal)
  78. a.head = &first
  79. a.tail = &first
  80. a.cursor = &first
  81. a.length = 1
  82. return a
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement