w3resource

C Exercises: Reverse a singly linked list in pairs

C Singly Linked List : Exercise-31 with Solution

Write a C program to reverse a singly linked list in pairs.

Sample Solution:

C Code:

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

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

struct Node* newNode(int data) {
struct Node* temp = (struct Node*) malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
return temp;
}

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

void reverse_Pairs(struct Node** head) {
    if(*head == NULL || (*head)->next == NULL) return;
    
    struct Node* temp = *head;
    *head = (*head)->next;
    temp->next = (*head)->next;
    (*head)->next = temp;
    
    struct Node* prev = temp;
    temp = temp->next;
    while (temp != NULL && temp->next != NULL) {
        prev->next = temp->next;
        temp->next = temp->next->next;
        prev->next->next = temp;
        prev = temp;
        temp = temp->next;
    }
}

int main() {
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
head->next->next->next->next->next = newNode(6);
printf("Original List: ");
printList(head);
reverse_Pairs(&head);
printf("Reverse a singly linked list in pairs:\n");
printList(head);
struct Node* head1 = newNode(1);
head1->next = newNode(2);
head1->next->next = newNode(3);
head1->next->next->next = newNode(4);
head1->next->next->next->next = newNode(5);
printf("\nOriginal List: ");
printList(head1);
reverse_Pairs(&head1);
printf("Reverse a singly linked list in pairs:\n");
printList(head1);
return 0;
}

Sample Output:

Original List: 1 2 3 4 5 6 
Reverse a singly linked list in pairs:
2 1 4 3 6 5 

Original List: 1 2 3 4 5 
Reverse a singly linked list in pairs:
2 1 4 3 5 

Flowchart :

Flowchart: Reverse a singly linked list in pairs.
Flowchart: Reverse a singly linked list in pairs.

C Programming Code Editor:

Previous: Reorder even-numbered before odd in a singly linked list.
Next: Split a singly linked list into two halves.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.