- 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.
方法一、递归的解法
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* newHead = head->next;
head->next = swapPairs(head->next->next);
newHead->next = head;
return newHead;
}
方法二、非递归的解法
ListNode* swapPairs(ListNode* head) {
if(NULL == head || NULL == head->next)
{
return head;
}
ListNode* first = head;
ListNode* second = first->next;
ListNode* pre;
int count = 0;
while(first && second)
{
first->next = second->next;
second->next = first;
if(count == 0) //如果是最开始的两个节点,则需要更改头节点
{
head = second;
}
else //如果不是开始的两个节点,则在交换第二个节点时,需要将第二个节点插在上一轮交换的最后一个节点之后,用pre保存
{
pre->next = second;
}
pre = first; //更新pre节点
first = first->next;
if(first) //注意如果first已经为NULL了,如果不加入if判断则会出现runtime 的错误
{
second = first->next;
}
count++;
}
return head;
}