Thursday, September 15, 2016

Reverse a link list in C without using pointers

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
int sData;
struct node *next;
};
struct node *start=NULL;
struct node *temp=NULL;

void insert(int lValue)
{
struct node *temp1;
temp1=malloc(sizeof(struct node));
temp=start;
if(NULL == start)
{
start=temp1;
temp1->sData=lValue;
temp1->next=NULL;
}
else
{
while(temp->next != NULL)
{
temp=temp->next;
}
temp->next=temp1;
temp1->sData=lValue;
temp1->next=NULL;
}
}
void display()
{
struct node *temp=start;
if(NULL == temp)
{
printf("Link list is empty\n");
}
else
{
while(temp->next !=NULL)
{
printf("Element is [%d]\n",temp->sData);
temp=temp->next;
}
printf("Last Element is [%d]\n",temp->sData);

}
}
int linkedlist_len()
{
struct node *temp=start;
int len=0;
if(NULL == start)
{
return len;
}
else
{
while(temp->next !=NULL)
{
len++;
temp=temp->next;
}
len++;
}
return len;
}
void reverse()
{
int i=0;
int *arr;
int llength=0;
llength=linkedlist_len();
if(start == NULL )
{
printf("Link list is empty\n");
}
else
{
struct node *temp=start;
arr=malloc(llength*sizeof(int ));
for(i=0;i<llength;i++)
{
arr[i]=temp->sData;
temp=temp->next;
}
temp=start;
for(i=llength-1;i>=0;i--)
{
temp->sData=arr[i];
temp=temp->next;
}
free(arr);
}
}


int main()
{
int choice;
int lData;
while(1)
{
printf(" 1. For Insert into link list\n 2. Display link list \n 3. Reverse a link list Without Using Pointers\n 4. Exit\n\n Enter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter Element:\t");
scanf("%d",&lData);
insert(lData);
break;
case 2:
display();
break;
case 3:
reverse();
break;
case 4:
exit(0);
break;
default:
printf("Invalid choice\n");
break;
}
}
return 0;
}

No comments:

Post a Comment