Traverse a singly linked list from the beginning to the end and reverse all the increasing and decreasing sequence of components present in the list. Component is the collection of continuous elements either in increasing or decreasing order. Example: Let the list contains 1, 2, 3, 7, 4, 2, 9, 7, 8 elements. Here the components are “1, 2, 3, 7”, “4, 2”, “9, 7”, and “8”. The code should produce the list with elements 7, 3, 2, 1, 2, 4, 7, 9, 8.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
}*head;
void create_list(int n);
void traverse_list();
int main()
{
int n;
printf("Enter no of nodes: ");
scanf("%d", &n);
create_list(n);
printf("\nData in the list \n");
traverse_list();
return 0;
}
void create_list(int n)
{
struct node *newNode, *temp;
int data, i;
head = (struct node *)malloc(sizeof(struct node));
if(head == NULL)
{
printf("Unable to allocate memory.");
exit(0);
}
printf("Enter the data of node 1: ");
scanf("%d", &data);
head->data = data;
head->next = NULL;
temp = head;
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
printf("Enter the data of node %d: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->next = NULL;
temp->next = newNode;
temp = temp->next;
}
}
void traverse_list()
{
struct node *temp;
if(head == NULL)
{
printf("List is empty.");
return;
}
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data);
temp = temp->next;
}
}
Comments
Leave a comment