SAVITIBAI PHULE UNIVERSITY OF PUNE
S. Y. B.Sc. (Computer Science) Semester III
Practical Examination
SUBJECT: CS-233 Practical course based on CS231
/* Q2. There are lists where new elements are always appended at the end of the list. The list can be implemented as a circular list with the external pointer pointing to the last element of the list. Implement singly linked circular list of integers with append and display operations. The operation append(L, n), appends to the end of the list, n integers either accepted from user or randomly generated.*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node * create(struct node *head)
{
struct node *newnode = NULL, *temp = NULL;
newnode = (struct node*) malloc(sizeof(struct node));
if(newnode!=NULL)
{
printf("Enter node data");
scanf("%d",&(newnode->data));
newnode->next = NULL;
if(head == NULL)
{
head = newnode;
newnode->next = head;
}
else
{
temp = head;
while(temp->next != head)
{
temp = temp->next;
}
temp->next = newnode;
newnode->next = head;
}
}
return head;
}
struct node * append(struct node *head, int n)
{
struct node *newnode = NULL, *temp = NULL;
newnode = (struct node*) malloc(sizeof(struct node));
newnode->data = n;
newnode->next = NULL;
temp = head;
while(temp->next != head)
{
temp = temp->next;
}
temp->next = newnode;
newnode->next = head;
return head;
}
void display(struct node *head)
{
struct node *temp = head;
do
{
printf("%d\t", temp->data);
temp = temp->next;
}while(temp != head);
}
int main()
{
int num, i;
struct node *head = NULL;
printf("Enter the number of nodes in list: ");
scanf("%d", &num);
for(i = 0; i < num; i++)
head = create(head);
display(head);
printf("\n enter data to be append:");
scanf("%d",&num);
head = append(head, num);
display(head);
system("pause");
return 0;
}
No comments:
Post a Comment