Search Program on this blog

Thursday 27 August 2015

Linklist: Create node , Traverse List, Delete Node

/*   C Program to create linklist, Traversal and deletion

*/

#include<stdio.h>
#include<stdlib.h>
struct node{
  int data;
  struct node *next;
};

struct node * head=NULL;
void addNode(int x){
  struct node *newNode,*p;
  p=head;
  newNode=(struct node *)malloc(sizeof(struct node));
  newNode->data=x;
  newNode->next=NULL;
  if(head==NULL){    // if list is empty
    head=newNode;
    return;
  }
  else{
    while(p->next!=NULL){ //find the last node
      p=p->next;
    }
    p->next=newNode;   //add node at the end
  }
  return;
}

void deleteNode(int x){
  if(head==NULL){
     printf("The list is empty\n");
     return;
  }
  else{
    struct node *p=head,*q;
    q=p;
    while(p!=NULL){
      //if element is first
      if(head->data==x){
        if(head->next!=NULL){  //if there are more nodes
          q=p;
          p=p->next;
          free(q);
          head=p;
          return;
        }
        else if(head->next==NULL){  //if head is the only node
          free(p);
          head=NULL;
          return;
        }
      }
      else if(p->data==x){
        if(p->next!=NULL){    //if node is not the last node
          q->next=p->next;
          free(p);
          return;
        }
        else if(p->next==NULL){  //if node is the last node
          free(p);
          q->next=NULL;
          return;
        }
      }
      q=p;
      p=p->next;
    }
    printf("Element not found\n");
    return;   
  }
}
void traverse(){
  if(head==NULL){
    printf("The list is empty\n");
  }
  else{
    struct node *p=head;
    do{
      printf("%d ",p->data);
      p=p->next;
    }while(p!=NULL);
    printf("\n");
  }
}
    
int main(){
  int choice;
  int x;
  while(1){
    printf("1)Add node\n2)Delete node\n3)Traverse list\n4)exit\n");
    scanf("%d",&choice);
    switch(choice){
      case 1:printf("Enter element to add\n");
             scanf("%d",&x);
      addNode(x);
        break;
      case 2:printf("Enter the node to be deleted\n");
             scanf("%d",&x);
             deleteNode(x);
        break;
      case 3:traverse();
        break;
      case 4:exit(1);
      default:printf("Enter valid choice\n");
    }
  }
  return 0;
}

No comments:

Post a Comment