C Code for reversing linked list using head


//implementing linked list using head
//printing recursive
//printing reverse recursive

#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};

void insert(struct node **,int );
//void display(struct node *head)
//void displayReverse(struct node *head);

int main()
{
printf("\n\n");
struct node *head=NULL;
insert(&head,10);
insert(&head,30);
insert(&head,19);
insert(&head,12);
insert(&head,99);

display(head);
printf("\n\n");

displayReverse(head);
printf("\n\n");

delete(&head);
printf("\n\n");

//display(head);
//printf("\n\n");
return 0;
}




void insert(struct node **head,int d)
{
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=d;
if(*head==NULL)
{
*head=newnode;
(*head)->next=NULL;
}
else
{
newnode->next=*head;
*head=newnode;
}
}

void display(struct node *head)
{
//printf("List in actual order is:\n");
printf("%d ",head->data);
if(head->next==NULL)
{
return;
}
else
{
display(head->next);
}
}

void displayReverse(struct node *head)
{
//printf("%d ",head->data);
if(head==NULL)
return;
else
displayReverse(head->next);
//printf("List in reversed order is:\n");
printf("%d ",head->data);
}


void delete(struct node **head)
{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}
/*
99 12 19 30 10
10 30 19 12 99 */

No comments:

Post a Comment