ramytamer

Double Linked List

Apr 21st, 2014
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.29 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define TYPE int
  6.  
  7. typedef struct Node{
  8.     TYPE data;
  9.     struct Node *next;
  10.     struct Node *back;
  11. }Node;
  12.  
  13. void initialize(Node *&head){ head=NULL; }
  14.  
  15. void addToStart(Node *&head,TYPE val){
  16.     Node *newNode = (Node*) malloc(sizeof(Node));
  17.     newNode->next = head;
  18.     newNode->back = NULL;
  19.     newNode->data = val;
  20.     head = newNode;
  21. }
  22.  
  23. void addToLast(Node *&head,TYPE val){
  24.     Node *newNode = (Node*) malloc(sizeof(Node));
  25.     newNode->next = NULL;
  26.     newNode->data = val;
  27.     if(!head) {
  28.         head = newNode;
  29.         newNode->back = NULL;
  30.     }else{
  31.         Node *p = head;
  32.         while(p->next) p = p->next; // enta wa2f 3nd el a5er
  33.         newNode->back = p;
  34.         p->next = newNode;
  35.     }
  36. }
  37.  
  38. void display(Node *head){
  39.     if(!head)
  40.         printf("EMPTY LIST.\n");       
  41.     else{
  42.         printf("List: ");
  43.         while(head){
  44.             printf("[%d]->",head->data );
  45.             head = head->next;
  46.         }
  47.         printf("\b\b  \n");
  48.     }
  49. }
  50.  
  51. void deleteFromStart(Node *&head){
  52.     (head->next)->back = NULL;
  53.     Node *node = head;
  54.     head = head->next;
  55.     free(node);
  56. }
  57.  
  58. void buildList(Node *&head,int lim){
  59.     int i; for(i=0;i<=lim;i++) addToStart(head,i);
  60. }
  61.  
  62. int main(){
  63.     system("CLS"); printf("\n");
  64.     Node *list; initialize(list);
  65.     buildList(list,5);
  66.     display(list);
  67.     deleteFromStart(list);
  68.     display(list);
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment