#include <stdio.h>
#include
<stdlib.h>
{
int data;
struct Node* next;
};
struct
Node* createNode(int value)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
void
insertEnd(struct Node** head, int value)
{
struct Node* newNode = createNode(value);
if (*head == NULL) *head = newNode;
else
{
struct Node* current = *head;
while (current->next != NULL)
current = current->next;
current->next = newNode;
}
}
struct
Node* reverseList(struct Node* head)
{
struct Node *prev = NULL, *current = head,
*next;
while (current)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
void
displayList(struct Node* head)
{
while (head != NULL)
{
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
void
main()
{
struct Node* head = NULL;
int num, value;
printf("Enter number of nodes:
");
scanf("%d", &num);
for (int i = 0; i < num; i++)
{
printf("Enter value for node %d:
", i + 1);
scanf("%d", &value);
insertEnd(&head, value);
}
printf("Original list elements:
");
displayList(head);
struct Node* reversedHead =
reverseList(head);
printf("Reversed list elements:
");
displayList(reversedHead);
while (reversedHead != NULL)
{
struct Node* temp = reversedHead;
reversedHead = reversedHead->next;
free(temp);
}
}
No comments:
Post a Comment