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) return nullptr; ListNode* nh = new ListNode(0); nh->next = head; ListNode* h0 = nh; ListNode* h1 = head; ListNode* h2 = head->next; while(h2 != nullptr) { h1->next = h2->next; h2->next = h1; h0->next = h2; h0 = h1; h1 = h1->next; h2 = (h1 ? h1->next : nullptr); } h0 = nh->next; delete nh; return h0; } };