问题
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.
代码
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if (!head) {
return NULL;
}
if (head->next == NULL) {
return head;
}
ListNode *returnNode = NULL;
ListNode *lastNode = NULL;
while (head) {
if (head->next) {
if (!returnNode) {
returnNode = head->next;
head->next = returnNode->next;
returnNode->next = head;
lastNode = head;
}
else
{
lastNode->next = head->next;
head->next = head->next->next;
lastNode->next->next = head;
lastNode = head;
}
}
else
{
break;
}
head=head->next;
}
return returnNode;
}
};
分析
链表,没有什么难度,一次性通过~~
总结
n/a