Skip to main content
Search
Search This Blog
Livecodo
Pages
Home
Courses
Blog
About us
More…
Share
Get link
Facebook
X
Pinterest
Email
Other Apps
May 02, 2024
Write a program to Reverse a singly Linked list.
#include
#include
struct Node { int data; struct Node* next; }; struct Node* createNode(int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (newNode == NULL) { printf("Memory allocation failed.\n"); exit(1); } newNode->data = data; newNode->next = NULL; return newNode; } int insertAtBeginning(struct Node** head, int data) { struct Node* newNode = createNode(data); newNode->next = *head; *head = newNode; } int printList(struct Node* head) { while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); } struct Node* reverseList(struct Node* head) { struct Node *prevNode = NULL, *currNode = head, *nextNode = NULL; while (currNode != NULL) { nextNode = currNode->next; currNode->next = prevNode; prevNode = currNode; currNode = nextNode; } return prevNode; } int main() { struct Node* head = NULL; insertAtBeginning(&head, 10); insertAtBeginning(&head, 20); insertAtBeginning(&head, 30); insertAtBeginning(&head, 40); printf("Original List: "); printList(head); head = reverseList(head); printf("Reversed List: "); printList(head); struct Node* temp; while (head != NULL) { temp = head; head = head->next; free(temp); } return 0; }
Popular Posts
March 26, 2024
Dynamic Memory allocation in C
May 18, 2024
Searching and sorting Algorithm in C