- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to swap nodes of a linked list pair wise in C++
Suppose we have a linked list. We have to swap every two adjacent nodes (pair) and return its head. Here the constraint is that, we cannot modify the value of the nodes, only the node itself can be changed. So if the list is like [1,2,3,4], then the resultant list will be [2,1,4,3].
To solve this, we will follow these steps −
- if head is not present, then return head
- first := head, second := next of head, dummy is one new node with value -1
- next of dummy := first, and prev := dummy
- while second is not null
- temp := next of second
- next of first := next of second
- next of second := first
- next of prev := second
- prev := first
- if temp is not null, then first := temp and second := next of temp, otherwise break
- return next of dummy
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class ListNode{ public: int val; ListNode *next; ListNode(int data){ val = data; next = NULL; } }; ListNode *make_list(vector<int> v){ ListNode *head = new ListNode(v[0]); for(int i = 1; i<v.size(); i++){ ListNode *ptr = head; while(ptr->next != NULL){ ptr = ptr->next; } ptr->next = new ListNode(v[i]); } return head; } void print_list(ListNode *head){ ListNode *ptr = head; cout << "["; while(ptr->next){ cout << ptr->val << ", "; ptr = ptr->next; } cout << "]" << endl; } class Solution { public: ListNode* swapPairs(ListNode* head) { if(!head)return head; ListNode* first= head; ListNode* second = head->next; ListNode* dummy = new ListNode(-1); dummy->next = first; ListNode* prev = dummy; while(second){ ListNode* temp = second->next; first->next = second->next; second->next = first; prev->next = second; prev = first; if(temp){ first = temp; second = temp ->next; } else break; } return dummy->next; } }; main(){ Solution ob; vector<int> v = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; ListNode *head = make_list(v); print_list(ob.swapPairs(head)); }
Input
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
Output
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13,]
Advertisements