Repository navigation
Expand file tree
/
Copy pathswap.cpp
More file actions
88 lines (67 loc) · 1.3 KB
/
Copy pathswap.cpp
File metadata and controls
88 lines (67 loc) · 1.3 KB
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
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node *next;
};
struct node *end;
void begin(struct node **head,int data){
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=data;
newnode->next=NULL;
if(*head==NULL){
*head=newnode;
return;
}
newnode->next=*head;
*head=newnode;
return;
}
void display(struct node *head){
struct node *temp=head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
void swap(struct node **head,int x,int y){
if(x==y)
return;
struct node *prevx=NULL,*currx=*head,*prevy=NULL,*curry=*head;
while(currx && currx->data!=x){
prevx=currx;
currx=currx->next;
}
while(curry && curry->data!=y){
prevy=curry;
curry=curry->next;
}
if(currx==NULL || curry==NULL)
return;
if(prevx!=NULL)
prevx->next=curry;
else
*head=curry;
if(prevy!=NULL)
prevy->next=currx;
else
*head=currx;
struct node *temp=curry->next;
curry->next=currx->next;
currx->next=temp;
}
int main(){
struct node *head=NULL;
int n;
cin>>n;
for(int i=0;i<n;i++){
int d;
cin>>d;
begin(&head,d);
}
display(head);
swap(&head,8,20);
display(head);
return 0;
}