give me the code in c language to effeciently reverse the contents of a list and store…
- User
give me the code in c language to effeciently reverse the contents of a list and store again in the same list
Assistant
To efficiently reverse the contents of a list and store them again in the same list in C language, you can use an iterative approach. Here's a sample code to achieve this:
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; void reverseList(struct Node **head) { struct Node *prevNode = NULL, *curNode = *head, *nextNode; *head = NULL; while (curNode != NULL) { nextNode = curNode->next; curNode->next = prevNode; prevNode = curNode; curNode = nextNode; } *head = prevNode; } void printList(struct Node *head) { while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); } int main() { struct Node *head = NULL; int i; for (i = 0; i < 5; i++) { struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); newNode->data = i * 2; newNode->next = head; head = newNode; } printf("Original list: "); printList(head); reverseList(&head); printf("Reversed list: "); printList(head); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.