Thursday, August 16, 2012

Delete all matching elements in the Linked List


// INPUT : 1->2->3->4->5
// OUTPUT : 2->3->4->5 for deleteNode(head,1);

#include<stdio.h>
#include<stdlib.h>

typedef struct node{
 int data;
 struct node *next;
}Node;

Node* newNode(int data){
 Node *n = (Node*)malloc(sizeof(Node));
 n->data = data;
 n->next = NULL;
 return n;
}

void buildList(Node **headRef){
 int i;
 for(i=10;i>0;i--){
  Node *n = newNode(i);
  n->next = *headRef;
  *headRef = n;
 }
}

void freeMem(Node *head){
    Node *temp;
    while(head != NULL){
        temp = head;
        head = head->next;
        free(temp);
    }
}

void display(Node *head){
 while(head->next != NULL){
  printf("%d->",head->data);
  head = head->next;
 }
 printf("%d\n",head->data);
}

Node* deleteNode(Node* head,int data){
Node* temp;
Node* n;
temp = head;
while(temp != NULL){
if(temp->data == data){
head = temp->next;
temp->next = NULL;
free(temp);
temp = head;
continue;
}
n = temp->next;
if(n != NULL && n->data == data){
temp->next = n->next;
n->next = NULL;
free(n);
continue;
}
if(n == NULL){
break;
} else {
temp = temp->next;
}
}
return head;
}

int main(){
 Node *head = NULL;
 buildList(&head);
 display(head);
 head = deleteNode(head,1);
 display(head);
 freeMem(head);
 return 0;
}

No comments:

Post a Comment