:: [intv] Link list ::
HOME


[Date Prev][Date Next][Date Index]

[intv] Link list


//Objective: Linked List
#include <stdio.h>

typedef struct node_T {
  int key;
  struct node_T *nxt;
} node;

//Print the LL.
void printFwdLL(node *H);

//Print LL in reverse.
void printRevLL(node *H);

//Add a node to the front of the LL.
node *addNode(node *H, int data);

//Reverse a LL
node *reverseLL(node *H);

//Delete a node from the LL. Note that the Head is sent as pointer-to-a pointer.
int delNode(node **H, int data);


int main(void){ node *Head; //Head pointer Head = NULL;

  Head = addNode(Head, 5);
  Head = addNode(Head, 7);
  Head = addNode(Head, 8);
  Head = addNode(Head, 9);
  Head = addNode(Head, 2);

  printFwdLL(Head);
  //  printRevLL(Head);

  //  Head = reverseLL(Head);
  //printFwdLL(Head);

  if (-1 ==  delNode(&Head, 11)){
    printf("Node 2 cannot be deleted..\n");
  }
  printFwdLL(Head);


}

node *addNode(node *H, int data){
  node *tmp;
  tmp = (node *)malloc(sizeof(node));
  if (!tmp){
    printf("ERROR: Memory cannot be allocated...exiting\n");
    exit(-1);
  }
  tmp->key = data;
  if (H == NULL){
    tmp->nxt = NULL;
  }else{
    tmp->nxt = H;
  }
  H = tmp;
  return H;
}

node *reverseLL(node *H){
  node *newH;
  node *curr, *next;

  if (!H) return H;  //List is Null
  if (!H->nxt) return H; //List Contains only one element

  newH = H;
  curr = H->nxt;
  newH->nxt = NULL;

  while (curr->nxt){
    next = curr->nxt;
    curr->nxt = newH;
    newH = curr;
    curr = next;
  }
  curr->nxt = newH;
  newH = curr;
  return newH;
}

int delNode(node **H, int data){
  node *prev, *curr, *next;
  int foundFlg = 0;

  //Case1: List is Empty. Return -1.
  if (!*H) return -1;  //List is Null

  //Case2: Key matches the Head Element. Head pointer will need to be changed.
  if (data == (*H)->key){
    next = (*H)->nxt;
    free(*H);
    (*H) = next;
    return 1;
  }

  //Case3: Key Matches anyother element in the list.
  prev = *H;
  curr = (*H)->nxt;
  next = curr->nxt;

  while (1){
    if (data == curr->key){
      prev->nxt = next;
      free(curr);
      foundFlg = 1;
      break;
    }
    if (!curr->nxt) break;
    prev = curr;
    curr = next;
    next = curr->nxt;
  }
  if (foundFlg) {return 1;}else{ return -1;}

}


void printFwdLL(node *H){ node *tmp; tmp = H; while(tmp){ printf("%d => ", tmp->key); tmp = tmp->nxt; } printf("NULL\n");

}


void printRevLL(node *H){ if (!H->nxt) { printf("%d ==> ", H->key); return; } printRevLL(H->nxt); printf("%d ==> ", H->key); }


Comments and corrections are appreciated and can be sent to papers@mia.ece.uic.edu. Click here for ©opyright information.