登录
首页 >  Golang >  Go问答

Golang 链表中尾部元素未被成功插入

来源:stackoverflow

时间:2024-02-24 16:24:27 259浏览 收藏

本篇文章给大家分享《Golang 链表中尾部元素未被成功插入》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我在 golang 中有一个双向链表。就是这个了

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

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

我想在列表的最后插入元素。所以我需要做三件事:

--改变当前last的next指针

-- 改变新node的prev指针

-- 将新节点指向nil

我正在做完全相同的事情,但是 prev 指针似乎没有指向前一个最后一个节点,因为它没有从后面打印。你能发现问题所在吗?我在最后添加了“粉红色”这个词。这就是它的功能。

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++
    }

}

这些是打印语句

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

正确答案


编辑----
您已经有了列表的尾部,无需使用 for currentNode.next != nil {} 进行处理。只需将 tail.nextlist.tail 指向 newNode 即可。

在 else 块中,您需要设置 listReceiver.tail = &newNode

在任何情况下,listReceiver.tail = &newNode 都应设置,以便可以位于 if-else 块之外

以上就是《Golang 链表中尾部元素未被成功插入》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>