繁体   English   中英

如何在LinkedList的末尾插入值?

[英]How do you insert a value at the end of a LinkedList?

我试图在LinkedList的末尾添加一个值。 我知道如何迭代到LinkedList的末尾,但是我不确定从那里去哪里。

void llist_insert_last(LinkedList * list, int value) {
  ListNode * e = list->head;
  while(e != NULL) {
    e = e->next;
  }
}

循环到列表末尾的循环是好的,但是它走的太远了一步,指针最终以NULL结尾。 这使它无用,因为它不再指向有效的列表节点。

您需要找到最后一个元素,即伪代码,例如:

def appendNode (list, payload):
    // Create the new node with payload.

    node = new node()
    if node == NULL:
        handleOutOfMemoryIntelligently()
    node.payload = payload
    node.next = NULL

    // Handle special case of empty list,
    //   needs pass by reference for list

    if list == NULL:
        list = node
        return

    // Find the last item in the list (the one that
    //   has a NULL next pointer) and adjust it to
    //   point to the new node.

    while list.next != NULL:
        list = list.next
    list.next = node

如果要执行堆栈操作,则在链接列表的末尾插入一个值,如下所示:

 ListNode *prev = list->head;  
 /* Make sure to check the return value of malloc in real life */
 ListNode *curr = malloc(sizeof(LinkedNode));
 curr->data = value;
 curr->next = prev;

您需要将指针传递给指针以修改list的值

但是,如果您要排队,则要迭代到列表的末尾,您应该这样做:

ListNode * e = list->head;
while(e->next != NULL) e = e->next;

/* set E to a ListNode */

当然,有几种解决方案,但我最喜欢的是双重间接解决方案。 它使用了额外的间接级别,可以对称地访问头指针和下一个指针:

void llist_insert_last(LinkedList * list, int value)
{
    ListNode ** e = &list->head;
    while((*e) != NULL) {
        e = &(*e)->next;
    }
    *e = llist_node_allocate(value);  //need implementation details.
    *e->next = NULL;
}

对于试图更好地掌握指针的人来说,这是一个很好的教学练习:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM