forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap_nodes.cpp
100 lines (76 loc) · 1.92 KB
/
swap_nodes.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 linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields.
It may be assumed that all keys in linked list are distinct.
Examples:
Input: 10->15->12->13->20->14, x = 12, y = 20
Output: 10->15->20->13->12->14
Input: 10->15->12->13->20->14, x = 10, y = 20
Output: 20->15->12->13->10->14
Input: 10->15->12->13->20->14, x = 12, y = 13
Output: 10->15->13->12->20->14
*/
#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;
}
}
struct node* swapNodes(struct node* head, int x, int y){
if(x==y) return head;
struct node *preX=NULL, *curX=head, *preY=NULL, *curY=head;
while(curX!=NULL && curX->data!=x){
preX=curX;
curX=curX->next;
}
while(curY!=NULL && curY->data!=y){
preY=curY;
curY=curY->next;
}
if(curX==NULL || curY==NULL) return head;
if(preX!=NULL) preX->next=curY;
else head=curY;
if(preY!=NULL) preY->next=curX;
else head=curX;
struct node* tmp=curY->next;
curY->next=curX->next;
curX->next=tmp;
return head;
}
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);
}
int x, y;
cin>>x>>y;
disp(head);
cout<<endl;
head=swapNodes(head,x,y);
disp(head);
}