Professional Documents
Culture Documents
Login/Register GATE
Practice CS Placements Videos Contribute
Menu
METHOD 1 (Iterative)
Start from the head node and traverse the list. While traversing swap data of each node with its next nodes data.
C/C++
/* C program to pairwise swap elements in a given linked list */
#include<stdio.h>
#include<stdlib.h>
/* UTILITY FUNCTIONS */
/* Function to swap two integers */
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
pairWiseSwap(start);
return 0;
}
Run on IDE
Java
Python
Output:
METHOD 2 (Recursive)
If there are 2 or more than 2 nodes in Linked List then swap the first two nodes and recursively call for rest of the list.
The solution provided there swaps data of nodes. If data contains many fields, there will be many swap operations.
See this for an implementation that changes links rather than swapping data.
Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
Recommended Posts:
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Load Comments
Trending Content
Longest Common Subsequence
GATE CS Notes
Depth First Traversal or DFS for a Graph
Reverse a linked list
Popular Categories
Interview Experiences
Dynamic Programming
Greedy Algorithms
Backtracking
Pattern Searching
Geometric Algorithms
Searching
Sorting
Analysis of Algorithms
Mathematical Algorithms
Randomized Algorithms
Recursion
Game Theory
ads by BSA
Tags
Advanced Data Structure Amazon Aptitude Aptitude Arrays Bit Magic C C C++ C++ Quiz Computer Networks CPP-
Library C Quiz Data Structures Data Structures DBMS Dynamic Programming Experienced GBlog Geometric Graph Hash
Internship Interview Experiences Java Linked Lists Mathematical Matrix MCQ Microsoft number-
digits Operating Systems Program Output Project Puzzles Python QA - Placement Quizzes QA - Placement Quizzes School
Programming Searching Sorting STL Strings Technical Scripter Trees
Advertise Here
Recent Comments
@geeksforgeeks, Some rights reserved Contact Us! About Us! Careers! Privacy Policy