Advertisement
Guest User

Untitled

a guest
May 4th, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct node
  6. {
  7.   node* next;
  8.   char* key;
  9. };
  10.  
  11. struct list
  12. {
  13.   node* first;
  14.   int size;
  15. };
  16.  
  17. list* createList()
  18. {
  19.   list* l = (list*)malloc(sizeof(list));
  20.   l->first = NULL;
  21.   l->size = 0;
  22.   return l;
  23. }
  24.  
  25. node* createNode(char *k)
  26. {
  27.   node* n = (node*)malloc(sizeof(node));
  28.   n->next = NULL;
  29.   n->key = k;
  30.   return n;
  31. }
  32.  
  33. void addFirst(list* l, char* key)
  34. {
  35.   node* x = createNode(key);
  36.   if (l->size == 0)
  37.   {
  38.     l->first = x;
  39.   }
  40.   else
  41.   {
  42.     x->next = l->first;
  43.     l->first = x;
  44.   }
  45.   l->size++;
  46. }
  47.  
  48. void deleteList(list* l)
  49. {
  50.     node* p = l->first;
  51.     node* temporary;
  52.     while (p->next!=NULL)
  53.     {
  54.         temporary=p->next;
  55.         p->key=NULL;
  56.         p->next=NULL;
  57.         l->size--;
  58.         free(p);
  59.         p=temporary;
  60.     }
  61.     l->size=0;
  62.     l->first=NULL;
  63.     free(l);
  64. }
  65.  
  66. void showList(struct list* l)
  67. {
  68.     node* p = l->first;
  69.     while (p!=NULL)
  70.     {
  71.         printf("%s ",p->key);
  72.         p=p->next;
  73.     }
  74. }
  75.  
  76. void copyPlus(struct list* l,char *ch)
  77. {
  78.     node* p = l->first;
  79.     addFirst(l,ch);
  80.     while (p!=NULL)
  81.     {
  82.         int len1=strlen(p->key);
  83.         int len2=strlen(ch);
  84.         char * cat = (char*)malloc(len1+len2+1);
  85.         strcpy(cat,p->key);
  86.         strcat(cat,ch);
  87.         cat[len1+1] = '\0';
  88.         printf("[%s] \n",cat);
  89.         addFirst(l,cat);
  90.         printf("{%s} \n",l->first->key);
  91.         p=p->next;
  92.     }
  93. }
  94.  
  95. int main(void)
  96. {
  97.     struct list *A=createList();
  98.     addFirst(A,"1");
  99.     addFirst(A,"2");
  100.     addFirst(A,"4");
  101.     copyPlus(A,"3");
  102.     printf("=%s= \n",A->first->key); //this one works!
  103.     printf("=%s= \n",A->first->next->key);
  104.     printf("=%s= \n",A->first->next->next->key);
  105.     showList(A);
  106.     deleteList(A);
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement