Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5dae261

Browse files
Merge pull request #122 from thecoderebel/thecoderebel-patch-1
Create #34- swap-nodes.cpp
2 parents 6ecf19c + da8f8a3 commit 5dae261

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
//Problem statement
2+
3+
//Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
4+
//Example-
5+
6+
//Input: 1->2->3->4
7+
//Output: 2->1->4->3
8+
9+
//Solution
10+
11+
class Solution {
12+
public:
13+
ListNode* swapPairs(ListNode* head) {
14+
if(!head or !head->next){
15+
return head;
16+
}
17+
//Check and replace the node to its next node
18+
ListNode*a= head;
19+
ListNode*b= head;
20+
b= a->next;
21+
a->next= b->next;
22+
b->next= a;
23+
head= b;
24+
//Swap the node
25+
a->next= swapPairs(a->next);
26+
return head;
27+
28+
}
29+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /