Skip to content

Commit 3eaa9c2

Browse files
authored
Create 1721_SwappingNodes_in_LinkedList.cpp
1 parent 820c75b commit 3eaa9c2

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
//Method one
2+
/**
3+
* Definition for singly-linked list.
4+
* struct ListNode {
5+
* int val;
6+
* ListNode *next;
7+
* ListNode() : val(0), next(nullptr) {}
8+
* ListNode(int x) : val(x), next(nullptr) {}
9+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
ListNode* swapNodes(ListNode* head, int k) {
15+
ListNode*p=head;
16+
ListNode*q=head;
17+
int a=k-1;
18+
int l=0;
19+
while(p){
20+
l++,p=p->next;
21+
}
22+
int b=(l-k);
23+
24+
p=head;
25+
while(a){
26+
p=p->next;
27+
a--;
28+
}
29+
while(b){
30+
q=q->next;
31+
b--;
32+
}
33+
swap(p->val,q->val);
34+
return head;
35+
}
36+
};
37+
38+
39+
//method two another approach
40+
// slow fast pointer
41+
// k from end = ans 2k+1 from start

0 commit comments

Comments
 (0)