0% found this document useful (0 votes)
11 views4 pages

15 1

Uploaded by

Impana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

15 1

Uploaded by

Impana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

15) C program to reverse a singly linked list

CODE:

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};

struct Node* createNode(int data) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data = data;

newNode->next = NULL;

return newNode;

void printList(struct Node* head) {

struct Node* current = head;

while (current != NULL) {

printf("%d -> ", current->data);

current = current->next;

printf("NULL\n");

struct Node* reverseList(struct Node* head) {

struct Node* prev = NULL;

struct Node* current = head;

struct Node* next = NULL;

while (current != NULL) {

next = current->next;

current->next = prev;

prev = current;
current = next;

return prev;

void freeList(struct Node* head) {

struct Node* current = head;

struct Node* next;

while (current != NULL) {

next = current->next;

free(current);

current = next;

int main() {

struct Node* head = createNode(1);

head->next = createNode(2);

head->next->next = createNode(3);

head->next->next->next = createNode(4);

head->next->next->next->next = createNode(5);

printf("Original linked list:\n");

printList(head);

head = reverseList(head);

printf("Reversed linked list:\n");

printList(head);

freeList(head);

return 0;

OUTPUT:
ALGORITHM:

Step 1:start

Step 2:Initialization:

Step 3:Create three pointers:

prev (set to NULL), current (set to the head of the list), and next (initially uninitialized).

Step 4:Traversal and Reversal:

Step 5:While current is not NULL:

Set next to current->next (store the next node).

Change current->next to prev (reverse the link).

Move prev to current (advance prev to the current node).

Move current to next (advance current to the next node).

Step 6:Return New Head:

After the loop, prev will be pointing to the new head of the reversed list. Return prev.

TRACING:

You might also like