Linked List Operations

 

// linked list

List Create()

void Insert(int x, List L)

void Delete(int x, List L)

int IsEmpty(List L)

int IsLast(Position P, List L)

Position Find(int x, List L)

Position FindPrevious(int x, List L)

void Display(List L)

void DeleteList(List L)

 

// linked list

 

#include<stdio.h>

#include<conio.h>

 

struct Node

{

          int element;

          struct Node *Next;

};

 

typedef struct Node *Position, *List;

//typedef PtrToNode Position;

//typedef PtrToNode List;

 

 

int IsEmpty(List L)

{

          return (L->Next == NULL);

}

 

int IsLast(Position P, List L)

{

          return (P->Next == NULL);

}

 

Position Find(int x, List L)

{

          Position P;

          P = L->Next;

 

          while(P!=NULL && P->element!=x)

                   P = P->Next;

 

          return P;

}

 

Position FindPrevious(int x, List L)

{

          Position P;

          P = L;

          while(P->Next!=NULL && P->Next->element!=x)

                   P = P->Next;

 

          return P;

}

 

void Delete(int x, List L)

{

          Position P, Tmpcell;

          P = FindPrevious(x, L);

 

          if(!IsLast(P,L))

          {

                   Tmpcell = P->Next;

                   P->Next = Tmpcell->Next;

                   free(Tmpcell);

          }

}

 


 

void Insert(int x, List L)

{

          Position Tmpcell;

 

          Tmpcell = (struct Node *)malloc(sizeof(struct Node));

 

          if(Tmpcell == NULL)

                   printf("Error. Unable to allocate memory\n");

 

          Tmpcell->element = x;

          Tmpcell->Next = L->Next;

          L->Next = Tmpcell;

}

 

void DeleteList(List L)

{

          Position P, Tmp;

          P = L->Next;

          L->Next = NULL;

 

          while(P!=NULL)

          {

                   Tmp = P->Next;

                   free(P);

                   P = Tmp;

          }

}

 

 


 

List Create()

{

 

          List L;

          L = (struct Node *)malloc(sizeof(struct Node));

 

          if(L==NULL)

                   printf("Error. Unable to allocate mempry.\n");

 

          else

          {

                   L->element = -1;

                   L->Next = NULL;

          }

          return L;

}

 

void Display(List L)

{

          L = L->Next;

          if(L==NULL)

                   printf("Empty List.\n");

          else

          {

                   printf("Elements in List : ");

                   while(L!=NULL)

                   {

                             printf("%d ",L->element);

                             L = L->Next;

                   }

          }

}


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu