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 :


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?
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join