Nth node from the end of a Linked List in one Traversal
time complexity O(n)
#include<stdlib.h>
struct node
{
char data;
struct node *next;
}*head;
void insert(int num)
{
struct node* temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
temp->next=NULL;
if(head==NULL)
{
head=temp;
}
else
{
struct node* temp1=head;
while(temp1->next!=NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
}
}
int delete(int num)
{
struct node *temp,*prev;
temp=head;
while(temp!=NULL)
{
if(temp->data==num)
{
if(temp==head)
{
head=temp->next;
free(temp);
return 1;
}
else
{
printf("else Part 1/n");
prev->next=temp->next;
free(temp);
return 1;
}
}
else
{
printf("else Part 2/n");
prev=temp;
temp=temp->next;
}
}
return 0;
}
void display()
{
struct node *temp2;
temp2=head;
while(temp2!=NULL)
{
printf("%d ",temp2->data);
temp2=temp2->next;
}
}
void fromlast(int n)
{
int i;
struct node* temp=head;
struct node* start=head;
for(i=0;i<n;i++)
{
temp=temp->next;
}
while(temp!=NULL)
{
start=start->next;
temp=temp->next;
}
printf("%d",start->data);
}
int main()
{
int i,num;
int pos;
int n1,n2;
struct node *n;
head=NULL;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Delete\n");
printf("4.Nth node from the end\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d",&i)<=0){
printf("Enter only an Integer\n");
exit(0);
} else {
switch(i)
{
case 1:
printf("Enter the number to insert : ");
scanf("%d",&num);
insert(num);
break;
case 2:
if(head==NULL)
{
printf("List is Empty\n");
}
else
{
printf("Element(s) in the list are : ");
}
display(n);
break;
case 3:
if(head==NULL)
printf("List is Empty\n");
else{
printf("Enter the number to delete : ");
scanf("%d",&num);
if(delete(num))
printf("%d deleted successfully\n",num);
else
printf("%d not found in the list\n",num);
}
break;
case 4:
printf("Nth node from the end \n");
scanf("%d",&n);
fromlast(n);
break;
case 5:
exit(1);
}
}
}
return 0;
}
No comments:
Post a Comment