w3resource

C Exercises: Swap every two adjacent nodes of a singly linked list

C Singly Linked List : Exercise-40 with Solution

Write a C program to swap every two adjacent nodes of a given singly linked list.

Sample Solution:

C Code:

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

// Definition for singly-linked list.
struct Node {
    int data;
    struct Node* next;
};

struct Node* swap_pairs(struct Node* head) {
	// If the list is empty or has only one node, no swapping required
    if (!head || !head->next) return head; 
    
    struct Node *prev = NULL, *curr = head, *next = head->next;
    head = next;
    
    while (next) {
        curr->next = next->next;
        next->next = curr;
        if (prev) prev->next = next;
        prev = curr;
        curr = curr->next;
        if (curr) next = curr->next;
    }
    
    return head;
}

// Function to create a new node in the linked list
struct Node* newNode(int data) {
    struct Node* node = (struct Node*) malloc(sizeof(struct Node));
    node->data = data;
    node->next = NULL;
    return node;
}

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

int main() {
    // Create a sample linked list
    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);
    printf("Original List:\n");
    printList(head);
    head = swap_pairs(head);
    printf("\n\nUpdated List after swapping every two adjacent nodes:\n");
    printList(head);    
    return 0;
}

Sample Output:

Original List:
1 2 3 4 5 

Updated List after swapping every two adjacent nodes:
2 1 4 3 5 

Flowchart :

Flowchart: Swap every two adjacent nodes  of a singly linked list.
Flowchart: Swap every two adjacent nodes  of a singly linked list.

C Programming Code Editor:

Previous: Interleave elements of two linked lists alternatively.
Next: Reverse alternate k nodes of a singly linked list.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.