Problem
leetcode链接problem
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 == nullptr || head -> next == nullptr)
{
return head;
}
ListNode* consthead = head;
ListNode* pre = head;
ListNode* now = head -> next;
int label = 0;
while(now != nullptr)
{
if(label == 0)
{
pre->next = now ->next;
now->next = pre;
consthead = now;
if(pre -> next == nullptr)
{
break;
} else if(pre->next->next == nullptr)
{
break;
} else
{
now = pre ->next;
}
label = 1;
} else{
pre->next = now->next;
now->next = pre->next->next;
pre->next->next = now;
if(now -> next == nullptr)
{
break;
} else if(now->next->next == nullptr)
{
break;
} else
{
pre = now;
now = now ->next;
}
}
}
return consthead;
}
};