Programming Geek
Rated 4.7/5 based on 1446 reviews

Basic Operations On Linked List

Linked List is a data structure consisting of a group of nodes connected together. A node of linked list is consisted of data part and a pointer to next node. If there is only one node than the pointer to next node has value NULL. Usually in singly linked list, last node's pointer has NULL value. The pseudo code of a typical linked list is as:

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


A linked list can hold any type of data. This is one of the advantages of linked list over typical array. Linked list grows dynamically. Since the nodes are stored randomly, memory is utilized efficiently. A logical  representation of linked list is shown in the diagram.



The basic operation performed on linked list like traversal,appending, addition at beginning, deletion of a node etc is implemented in following C program.

//Basic operations performed on a lined list like traversal, addition, deletion 
/**
 *
 * @author VIKASH VIK VIKASHVVERMA
 */

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

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

void append(node**s,int num)
{
 node*temp;
 if(*s==NULL)
 {
 temp=(node*)malloc(sizeof(node));
 temp->data=num;
 temp->next=NULL;
 *s=temp;
 
 }
 else
 {
 temp=*s;
 
 while(temp->next!=NULL)
 temp=temp->next;
  
 node*temp1=(node*)malloc(sizeof(node));
 temp1->data=num;
 temp1->next=NULL;
 temp->next=temp1;
 }
}

void addatbeg(node**s,int num)
{
 node*temp=(node*)malloc(sizeof(node));
 temp->data=num;
 temp->next=*s;
 *s=temp;
}

void addafter(node**s,int num,int pos)
{
 node*temp;
 int count=1;
 temp=*s;
 
 while(count<pos)
 { 
  if(temp==NULL)
  {
   printf("\nless than %d elements",pos);
   exit(0);
  }
  temp=temp->next;
  count++;
 }
 
 node*temp1=(node*)malloc(sizeof(node));
 temp1->data=num;
 temp1->next=temp->next;
 temp->next=temp1;
}

void traverse(node*s)
{ printf("\n");
 while(s!=NULL)
 {
  printf("%d\t",s->data);
  s=s->next;
 }
}

void delete(node**s,int num)
{
 node*prev=NULL,*temp=NULL;
 temp=*s;
 
 while(temp!=NULL)
 {
  if(temp->data==num)
  {
   if(temp==*s)
   *s=temp->next;
   else
   prev->next=temp->next;
   
   free(temp);
   return;
  }
  else
  {
   prev=temp;
   temp=temp->next;
  }
  
 }
}
void main()
{
 node*n=NULL;
 
 append(&n,5);
 append(&n,7);
 append(&n,18);
 append(&n,12);
 append(&n,78);
 append(&n,-13);
 traverse(n);
 addatbeg(&n,25);
 traverse(n);
 addafter(&n,19,3);
 traverse(n);
 delete(&n,12);
 traverse(n);
 
}


No comments :

Post a Comment