forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpairwise_swap.cpp
100 lines (79 loc) · 2.03 KB
/
pairwise_swap.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Given a singly linked list of size N. The task is to swap elements in the linked list pairwise.
For example, if the input list is 1 2 3 4, the resulting list after swaps will be 2 1 4 3.
Input:
The first line of input contains the number of test cases T. For each test case, the first line of input contains the length of the linked list and the next line contains linked list data.
Output:
Output the linked list after swapping pairwise nodes.
User Task:
The task is to complete the function pairWiseSwap() which takes the head node as the only argument and returns the modified head.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= T <= 100
1 <= N <= 103
Example:
Input:
1
8
1 2 2 4 5 6 7 8
Output:
2 1 4 2 6 5 8 7
Explanation:
Testcase 1: After swapping each pair considering (1,2), (2, 4), (5, 6).. so on as pairs, we get 2, 1, 4, 2, 6, 5, 8, 7 as a new linked list.
*/
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node* next;
};
struct node* createList(struct node* head, int data){
struct node *tmp=(struct node*)malloc(sizeof(struct node));
tmp->data=data;
tmp->next=NULL;
if(head==NULL){
head=tmp;
return head;
}
struct node* p=head;
while(p->next!=NULL){
p=p->next;
}
p->next=tmp;
return head;
}
void disp(struct node* head){
struct node* p=head;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
}
void pairWiseSwap(struct node* head) {
if(head==NULL) return ;
struct node *p1=head, *p2=head->next;
while(p2!=NULL){
int tmp=p2->data;
p2->data=p1->data;
p1->data=tmp;
if(p2->next!=NULL && p2->next->next!=NULL){
p1=p2->next;
p2=p1->next;
} else break;
}
}
int main(){
struct node* head=NULL;
int n;
cin>>n;
for(int i=0;i<n;i++){
int data;
cin>>data;
head=createList(head, data);
}
disp(head);
cout<<endl;
pairWiseSwap(head);
disp(head);
}