/
swap-nodes-in-a-linked-list-without-swapping-data.cpp
102 lines (76 loc) · 1.63 KB
/
swap-nodes-in-a-linked-list-without-swapping-data.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
101
102
// MOT DONE
// Swap nodes in a linked list without swapping data
// http://www.geeksforgeeks.org/swap-nodes-in-a-linked-list-without-swapping-data/
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node *next;
};
void printList(node *head){
while(head){
cout<<head->data<<' ';
head = head->next;
}
cout<<endl;
}
void push(node **head, int data){
// allocate new node
node *x = new node;
// put in the data
x->data = data;
x->next = NULL;
// get another pointer to point to head.
node *last = *head;
// if the LL is empty, then make the new node as head.
if(*head==NULL){
*head = x;
return;
}
// else traverse till the last node.
while(last->next){
last = last->next;
}
// change the next of the last node.
last->next = x;
}
void swapNodes(node **head, int a, int b){
node *temp=NULL, *first=NULL, *second=NULL;
while((*head)!=NULL){
if((*head)->data == a){
first = (*head);
}
if((*head)->data == b){
second = (*head);
}
(*head) = (*head)->next;
}
if(first==NULL || second==NULL){
cout<<"No change"<<endl;
}
// swap(first->next, second->next);
swap(first->data, second->data);
}
int main(){
struct node *start = NULL;
/* The constructed linked list is:
1<-2<-3<-4<-5<-6<-7 */
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
printf("\n Linked list before calling swapNodes() ");
printList(start);
swapNodes(&start, 4, 3);
printf("\n Linked list after calling swapNodes() ");
printList(start);
return 0;
}
/*
Output
7 3 2
3 2
*/