Solution:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node* head=NULL;
struct node *cn()
{
struct node* n;
n=(struct node *)malloc(sizeof(struct node));
return(n);
}
int n; //size of linked list
void createnode() //Function to create Linked list.
{
int i,x;
struct node * temp,*newnode;
printf("Enter size of linked list :\n");
scanf("%d",&n);
printf("Enter elements of linked list :\n");
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(head==NULL) //checking in linked list is empty
{
head=cn();
head->data=x;
head->next=NULL;
temp=head;
}
else
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
temp=newnode;
}
}
}
void traverse() //Function to traverse Linked list.
{
struct node * temp;
temp=head;
printf("\n\nLinked list after deleting last node and adding it at beginnig.\n");
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
void deletenode() //Function to delete a node from Linked list.
{
struct node * temp,*temp1;
int i=1,x;
temp=head;
if(head==NULL)
{
printf("Linked list is empty. \n");
}
else
{
while((i<n-1) && (temp!=NULL))
{
temp=temp->next;
i++;
}
if(temp!=NULL)
{
temp1=temp->next;
temp->next=NULL;
}
}
temp1->next=head;
head=temp1;
}
int main()
{
int choice,a=0;
if(a==1)
{
printf("You have already created a Linked list.");
}
else
{ createnode();
a++;
}
deletenode();
traverse();
}
0 Comments