Advertisement
Guest User

Linked List Remove Function

a guest
Jun 20th, 2011
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. typedef struct Element{
  5.     struct Element *next;
  6.     int data;
  7. }Element;
  8.  
  9. int removeL(Element *elem);
  10.  
  11. Element *head, *tail;
  12.  
  13. int removeL(Element *elem){
  14.  
  15.     Element *cur=head;
  16.  
  17.     if (!elem)
  18.         return 1;
  19.    
  20.     if(elem==head){
  21.         head=elem->next;
  22.         free(elem);
  23.         if (!head)
  24.             tail=NULL;     
  25.         return 0;
  26.     }
  27.    
  28.     while(cur){
  29.         if (cur->next ==elem){
  30.             cur->next=elem->next;
  31.             free(elem);
  32.             if (cur->next==NULL)
  33.                 tail=cur;
  34.             return 0;
  35.         }
  36.         cur=cur->next;
  37.     }
  38.  
  39.     return 1;
  40. }
  41.  
  42. void printL(){
  43.     Element *cur=head;
  44.    
  45.     printf("List:");
  46.    
  47.     while(cur){
  48.         printf(" %d ",cur->data);
  49.         cur=cur->next;
  50.     }
  51.    
  52.     printf("\n");
  53. }
  54.  
  55. int main(){
  56.    
  57.     /* create a 3 element linked list */
  58.     head=(Element *)malloc(sizeof(Element *));
  59.     head->data=5;
  60.    
  61.     head->next=(Element *)malloc(sizeof(Element *));
  62.     head->next->data=6;
  63.    
  64.     head->next->next=(Element *)malloc(sizeof(Element *));
  65.     head->next->next->data=7;
  66.    
  67.     tail=head->next->next;
  68.    
  69.     /* print out the list */
  70.     printL();
  71.    
  72.     /* remove element (try head, head->next or head->next->next in the argument) */
  73.     removeL(head->next);
  74.    
  75.     /* reprint the modified list */
  76.     printL();
  77.    
  78.        
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement