Thread: How to use Linked List?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784

    Re: How to use Linked List?

    Originally posted by MKashlev

    Code:
    struct node* AppendNode(struct node** headRef, char var[50]) {
        struct node* current = *headRef;
        struct node* newNode;
        newNode = malloc(sizeof(struct node));
        newNode->data = var;
        newNode->next = NULL;
    // special case for length 0
        if (current == NULL) {
            *headRef = newNode;
        }
        else {
    // Locate the last node
            while (current->next != NULL) {
                current = current->next;
            }
            current->next = newNode;
        }
    }

    Code:
    void AppendNode(struct node** headp, char var[50]) {
        struct node *currentp, *previousp, *newp;
        currentp = previousp = newp = NULL;
        newp = malloc(sizeof(struct node) );
    //Perform deep copy
        strcpy( newp->data,var );
        newp->next = NULL;
    // special case for length 0
        if (*headp == NULL) {
            **headp = *newp;
        }
        else {
    // Locate the last node
      currentp = headp;
            while (current->next != NULL) {
      previousp = currentp;
                current = current->next;
            }
            previousp->next = newp;
        }
    }
    I forget, it's been ages, but the code for adding a node goes something like this. There are sure to be a few errors. I did not test the code, but this is the basic idea for appending a node to a linked list. You don't need to return the list because your using a pointer to a pointer. Someone else can fix the errors.
    Last edited by Troll_King; 08-06-2002 at 07:13 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ Linked list program need help !!!
    By dcoll025 in forum C++ Programming
    Replies: 1
    Last Post: 04-20-2009, 10:03 AM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  4. Template Class for Linked List
    By pecymanski in forum C++ Programming
    Replies: 2
    Last Post: 12-04-2001, 09:07 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM