简体   繁体   中英

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

I'm trying to add a value given to the end of a LinkedList. I know how to iterate to the end of the LinkedList but I'm not sure where to go from there.

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

Your loop that iterates to the end of the list is good, but it's going one step too far and the pointer is ending up as NULL. That makes it useless since it no longer points to a valid list node.

You need to find the last element, meaning pseudo-code such as:

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

If you're doing a stack, then inserting a value at the end of a linked list looks like this:

 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;

You'll need to pass a pointer to a pointer to modify the value of list

However, if you're doing a queue, to iterate to the end of the List you should do this:

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

/* set E to a ListNode */

There are several solutions of course, but my favorite is the double indirection solution. It uses an extra level of indirection to make the head pointer and the next pointers symmetically accessible:

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

This is a good teaching exercise for people trying to get better at pointers :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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