Write a program to reverse a linked list in c.



Write a program to reverse a linked list in c...

Answer / Paras Nath Verma

Here's an example of a C program that reverses a singly-linked list:

```c
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

void push(struct Node** head_ref, int new_data) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = new_data;
temp->next = (*head_ref);
(*head_ref) = temp;
}

void reverseList(struct Node **head) {
struct Node *prevNode = NULL, *currentNode = *head, *nextNode;

while (currentNode != NULL) {
nextNode = currentNode->next;
currentNode->next = prevNode;
prevNode = currentNode;
currentNode = nextNode;
}

*head = prevNode;
}

void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}

int main() {
struct Node* head = NULL;
push(&head, 10);
push(&head, 20);
push(&head, 30);
printf("Linked List: ");
printList(head);

reverseList(&head);
printf("Reversed Linked List: ");
printList(head);
return 0;
}

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More C Interview Questions

logic for x=y^n

1 Answers   Delphi,


what is an array

5 Answers  


C program to find frequency of each character in a text file?

6 Answers  


What is function prototype?

1 Answers  


write a program to print the one dimensional array.

1 Answers  


What are predefined functions in c?

1 Answers  


Write a function that will take in a phone number and output all possible alphabetical combinations

1 Answers   Motorola,


write a program to swap two variables a=5 , b= 10 without using third variable

5 Answers  


How do I declare a pointer to an array?

6 Answers   IBM,


25. It takes five minutes to pass a rumour from one person to two other persons. The tree of rumour continues. Find how many minutes does it take spread the rumour to 768 persons. ?

11 Answers   CTS, TCS,


how to solve "unable to open stdio.h and conio.h header files in windows 7 by using Dos-box software

1 Answers  


What are the different types of constants?

1 Answers  


Categories