-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPairwise_swap_elements_of_linked_list.cpp
More file actions
66 lines (60 loc) · 1.08 KB
/
Pairwise_swap_elements_of_linked_list.cpp
File metadata and controls
66 lines (60 loc) · 1.08 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
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
void append(Node** head,int new_data)
{
Node* new_node=new Node();
new_node->data=new_data;
new_node->next=NULL;
if(*head==NULL)
{
*head=new_node;
return;
}
Node* last=*head;
while(last->next!=NULL)
last=last->next;
last->next=new_node;
return;
}
void print(Node* head)
{
while(head!=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
}
Node* pairWiseSwap(Node* head)
{
if(head==NULL|| head->next==NULL)
return head;
Node* remain=head->next->next;
Node* new_head=head->next;
head->next->next=head;
head->next=pairWiseSwap(remain);
return new_head;
}
int main()
{
Node *head=NULL;
append(&head,9);
append(&head,8);
append(&head,7);
append(&head,6);
append(&head,5);
append(&head,4);
append(&head,3);
append(&head,2);
append(&head,1);
print(head);
cout<<"\nAfter Swap: \n";
head=pairWiseSwap(head);
print(head);
return 0;
}