mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
31 lines
736 B
C++
31 lines
736 B
C++
class Solution{
|
|
public:
|
|
ListNode* SwapNode(ListNode* head){
|
|
if(!head || !head->next) return head;
|
|
|
|
ListNode* dummy = new ListNode(0);
|
|
dummy->next = head;
|
|
|
|
ListNode* cur = head;
|
|
ListNode* prev = dummy;
|
|
|
|
while(cur && cur->next){
|
|
ListNode* nextPair = cur->next->next;
|
|
ListNode* second = cur->next;
|
|
|
|
second->next = cur;
|
|
cur->next = nextPair;
|
|
prev->next = second;
|
|
|
|
prev = cur;
|
|
cur = nextPair;
|
|
}
|
|
ListNode* newHead = dummy->next;
|
|
delete dummy;
|
|
return newHead;
|
|
}
|
|
};
|
|
|
|
//TC : O(n)
|
|
//SC : O(1)
|