给一个链表,两两交换其中的节点,然后返回交换后的链表。
样例
样例 1:
输入:1->2->3->4->null
输出:2->1->4->3->null
样例 2:
输入:5->null
输出:5->null
挑战
你的算法只能使用常数的额外空间,并且不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: a ListNode
* @return: a ListNode
*/
ListNode * swapPairs(ListNode * head) {
// write your code here
if(head == NULL)
return NULL;
if(head != NULL && head->next == NULL)
return head;
ListNode* ret = NULL;
ListNode* tail = NULL;
while(head)
{
if(head->next == NULL)
{
tail->next = head;
break;
}
ListNode* next = head->next->next;
if(ret == NULL)
{
ret = head->next;
ret->next = head;
tail = head;
tail->next = NULL;
}
else
{
tail->next = head->next;
tail = head->next;
tail->next = head;
tail = head;
tail->next = NULL;
}
head = next;
}
return ret;
}
};