[LeetCode]24. Swap Nodes in Pairs
题目:
Given a linked list, swap every two adjacent nodes and return its head.
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.
主要是要保存头结点以及交换的第二个结点后一个结点。
/** * 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 || !head->next) return head; ListNode first(0); ListNode *pre = &first; ListNode *cur1 = head, *cur2 = head->next; while(cur1 && cur2){ ListNode* node2Next = cur2->next; pre->next = cur2; cur2->next = cur1; cur1->next = node2Next; pre = cur1; if (!node2Next)break; cur1 = node2Next; cur2 = node2Next->next; } return (&first)->next; } };