ramytamer

SLL

Jun 18th, 2014
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define TYPE int
  5.  
  6. typedef struct Node{
  7.     TYPE data;
  8.     struct Node *next;
  9. }Node;
  10.  
  11. void reset(Node **lsHead);
  12. int isEmpty(Node **lsHead);
  13. void addToStart(Node **lsHead,TYPE val);
  14. void addToEnd(Node **lsHead,TYPE val);
  15. TYPE popStart(Node **lsHead);
  16. TYPE popEnd(Node **lsHead);
  17.  
  18. int main(){
  19.     system("clear");
  20.     Node *ls = NULL; reset(&ls);
  21.     addToStart(&ls,5);
  22.     addToStart(&ls,4);
  23.     addToEnd(&ls,6);
  24.     printf("pop end: %d\n", popEnd(&ls));
  25.     printf("pop start: %d\n", popStart(&ls));
  26.     printf("pop end: %d\n", popEnd(&ls));
  27.     return 0;
  28. }
  29.  
  30. void reset(Node **lsHead){ *lsHead = NULL; }
  31. int isEmpty(Node **lsHead){ return !*lsHead; }
  32. void addToStart(Node **lsHead,TYPE val){
  33.     Node *node = (Node*) malloc(sizeof(Node));
  34.     node->data = val;
  35.     node->next = *lsHead;
  36.     *lsHead = node;
  37. }
  38. void addToEnd(Node **lsHead,TYPE val){
  39.     Node *node = (Node*) malloc(sizeof(Node));
  40.     node->data = val; node->next = NULL;
  41.     if(isEmpty(lsHead))
  42.         *lsHead = node;
  43.     else{
  44.         Node *last = *lsHead;
  45.         while(last->next) last = last->next; // getting the latest node
  46.         last->next = node;
  47.     }
  48. }
  49. TYPE popStart(Node **lsHead){
  50.     if(!isEmpty(lsHead)){
  51.         TYPE val = (*lsHead)->data;
  52.         Node *start = *lsHead;
  53.         free(start);
  54.         *lsHead = (*lsHead)->next;
  55.         return val;
  56.     }
  57.     return 1<<31;
  58. }
  59. TYPE popEnd(Node **lsHead){
  60.     if(!isEmpty(lsHead)){
  61.         Node *preLast = *lsHead;
  62.         if(preLast->next && preLast->next->next)
  63.             while((preLast->next)->next)
  64.                 preLast = preLast->next;
  65.         Node * last = preLast->next;
  66.         if(!last){
  67.             // last node in list
  68.             TYPE val = preLast->data;
  69.             free(preLast);
  70.             reset(lsHead);
  71.             return val;
  72.         }else{
  73.             // not last node
  74.             TYPE val = last->data;
  75.             preLast->next = NULL;
  76.             free(last);
  77.             return val;
  78.         }
  79.  
  80.     }
  81.     return 1<<31;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment