Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
题意
将链表中每两个结点两两交换
题解
1 class Solution { 2 public: 3 ListNode* swapPairs(ListNode* head) { 4 ListNode*hh = head,*before=NULL; 5 while (head) { 6 ListNode*first = head, *second = head->next; 7 if (!second)break; 8 if (hh == first)hh = second; 9 first->next = second->next; 10 second->next = first; 11 if (before)before->next = second; 12 head = first->next; 13 before = first; 14 } 15 return hh; 16 } 17 };