Monday, February 2, 2015

circular singly linked list

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


struct node
{
int data;
struct node *link;

};

struct node *createNode(int data)
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=data;
p->link=NULL;

return p;
}

struct node * traverseTillEnd(struct node *head)  // return the last node pointer to the list
{
struct node *p1,*p2=NULL;

if(head==NULL) // return NULL if there is no element in the list
{
return NULL;
}
else if((head->link)==NULL)
{
return head;
}
else
{
p1=head;
p2=p1->link;

while(p2!=head)
{
p1=p1->link;
p2=p2->link;
}

return p1;
}


}


struct node * insertAtEnd(struct node *head,int data)
{

struct node *p=createNode(data);
struct node *temp=NULL;

// traverse till the end of the list. since it is the circular singly linked list, the traversal of ll is litle different.
if(head==NULL)
{
p->link=p;
return p;
}
else
{
temp=(traverseTillEnd(head));
p->link=temp->link;
(temp->link)=p;
}

return head;

}

void printList(struct node *head)
{
struct node *p1=NULL;


if(head==NULL)
{
printf("no element in the list");
}
else
{
p1=head;
printf("-%d-",(p1->data));
p1=p1->link;
while(p1!=head)
{
printf("-%d-",(p1->data));
p1=p1->link;
}
printf("\n");

}

}


int main(void)
{

struct node *head=NULL;
head=insertAtEnd(head,5);
head=insertAtEnd(head,3);
head=insertAtEnd(head,6);
head=insertAtEnd(head,1);
head=insertAtEnd(head,7);


printList(head);

return 0;
}

No comments:

Post a Comment