-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 743 ms (7.46%), Space: 180.2 MB (16.39%) - LeetHub
- Loading branch information
1 parent
c15454e
commit 737b4b2
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
1721-swapping-nodes-in-a-linked-list/1721-swapping-nodes-in-a-linked-list.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |