forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request 7oSkaaa#1093 from Hima-khalid/main
15 th day
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
...wapping Nodes in a Linked List/15- Swapping Nodes in a Linked List ( Ibrahim Khalid ).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,29 @@ | ||
// Author : Ibarhim Khalid | ||
class Solution { | ||
public: | ||
ListNode* swapNodes(ListNode* head, int k) { | ||
// to store values | ||
vector<int>v; | ||
int cnt=0; | ||
ListNode *temp = head; | ||
// move between values in linkedlist and store it in vector | ||
while(temp !=NULL){ | ||
v.push_back(temp->val); | ||
temp=temp->next; | ||
} | ||
// swapping the values of the kth node from the beginning and the kth node from the end | ||
swap(v[k-1],v[v.size()-k]); | ||
// pointer to index in vector | ||
int in=0; | ||
ListNode *tmp = head; | ||
// reorder linkedlist by modified vector | ||
while(tmp !=NULL){ | ||
tmp->val=v[in]; | ||
cout<<tmp->val<<" "; | ||
tmp=tmp->next; | ||
in++; | ||
} | ||
|
||
return head; | ||
} | ||
}; |