Given a linked list, swap every two adjacent nodes and return its head.
For example,
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
在处理这种问题时,我们通常加上一个h1头结点指向head,至于思路很清晰了就是隔一个去交换两个相邻结点,比如1->2->3->4->NULL,我们先通过指针交换1和2,再交换3和4,具体的操作流程如下:
曲线上的数字代表每次循环的步骤。
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *h1 = new ListNode(0);
h1->next = head;
ListNode *prev = h1, *cur = head;
while (cur&&cur->next)
{
prev->next = cur->next;
cur->next = cur->next->next; //确定后继新交换的起点,下面有cur=cur->next
prev->next->next = cur;
prev = cur;
cur = cur->next; //当前为新交换的起始点
}
return h1->next;
}
};