Home > Back-end >  Tail element not getting inserted at the last in Golang Linked List
Tail element not getting inserted at the last in Golang Linked List

Time:09-18

I have a doubly linked list in Golang. this is it

type node struct {
    value string
    next  *node
    prev  *node
}

type list struct {
    head   *node
    tail   *node
    length int
}

I want to insert element at the last of the list. So I need to do 3 things :

-- Change the next pointer of the current Last

-- Change the prev pointer of the new Node

-- point new node to nil

I am doing exactly the same but the prev pointers seems to not point to the previous last node because its not getting printed from the back. Can you spot the issue. I added the word "Pink" in the last. This is the function to it.

func (listReceiver *list) insertLast(incomingValue string) {
    printNewLine := fmt.Println
    newNode := node{value: incomingValue}

    currentNode := listReceiver.head

    if listReceiver.head == nil {
        listReceiver.head = &newNode
        listReceiver.tail = &newNode
        fmt.Printf("New head -- %s", listReceiver.head.value)
        printNewLine()
        listReceiver.length  
    } else {
        for currentNode.next != nil {
            printNewLine(currentNode.value)
            currentNode = currentNode.next
        }

        currentNode.next = &newNode
        newNode.next = nil
        newNode.prev = currentNode

        fmt.Printf("New Tail -- %s ", newNode.value)
        printNewLine()
        listReceiver.length  
    }

}

These are the print statements

Linked List From Front -- 
->R->Kanak->Z->Zubin->A->Nani->US->Arjun->Pink

Linked List From Tail -- 
->Arjun->US->Nani->A->Zubin->Z->Kanak->R

CodePudding user response:

EDIT----
You already have the tail of the list, no need to itreate with for currentNode.next != nil {}. Just point the tail.next and list.tail to newNode.


In else block you need to set listReceiver.tail = &newNode

In any case listReceiver.tail = &newNode should be set so can be outside the if-else block

  •  Tags:  
  • go
  • Related