Skip to content

Commit

Permalink
Time: 743 ms (7.46%), Space: 180.2 MB (16.39%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
Dipendra-Raghav committed May 15, 2023
1 parent c15454e commit 737b4b2
Showing 1 changed file with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
ListNode* temp=head;
int cnt=0;
while(temp)
{
temp=temp->next;
cnt++;
}
cnt=cnt-k+1;
ListNode* chk=head;
ListNode* first;
ListNode* last;
int t=1;
while(chk)
{
if(t==k)first=chk;
if(t==cnt)last=chk;
t++;
chk=chk->next;
}
int flag=first->val;
first->val=last->val;
last->val=flag;
return head;
}
};

0 comments on commit 737b4b2

Please sign in to comment.