Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Analysis:For example,
Given
1->2->3->4
, you should return the list as 2->1->4->3
.Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
The problem requires to swap node pairs, e.g., swap(node1, node2), swap(node3, node4). So the thing you need to be careful with is when the list has odd number of nodes, you need to stop traversing the list if there's only one node left.
Code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { if (head==NULL) return NULL; ListNode *prev=new ListNode(0); // a pesudo node prev->next=head; ListNode *newHead=prev; ListNode *cur1=head, *cur2=head->next; while(cur2!=NULL) { cur1=prev->next; cur2=cur1->next; swap(prev,cur1,cur2); if (cur1->next==NULL || cur1->next->next==NULL) break; prev=prev->next->next; } return newHead->next; } void swap(ListNode *prev, ListNode*cur1, ListNode*cur2) { ListNode *temp=cur2->next; cur2->next=cur1; cur1->next=temp; prev->next=cur2; } };
No comments:
Post a Comment