Monday, May 21, 2012

Link list: 3 steps of listAdd operation


 1. Allocate memory for the new element

                        - can be done in the add routine  

 2. Fill the structure data/prev/next fields for the new element

 3. Connect in the linklist as follows:


     Check listHead == 0 --> 1st elm --> both head and tail equal to the new elm
                                != 0  --> not 1st elm --> put in after tail. then this new elm become tail.




#include <stdio.h>
#include <stdlib.h> // for malloc

// minimum needed as follows:
typedef struct node {
  int data;
  struct node *next;
  struct node *prev;
} NodeType;

NodeType *listHead=0, *listTail=0; // this is convenient


int listAdd(int newData) {
    NodeType *newNode;

    newNode = (NodeType *) malloc(sizeof(NodeType));
   // TBD check NULL and return if so
    newNode->data = newData;
    newNode->next = 0;
    newNode->prev = 0;

    if(listHead == 0) {
       listHead = newNode;
       listTail = newNode;
       printf("1st node added (%d)\n", listHead->data);
       return 0;
    }

    listTail->next = newNode;
    newNode->prev = listTail;
    // do not forget to set new listTail
    listTail = listTail->next;

    return 0;
}

No comments:

Post a Comment