LeetCode-24.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.
两种解法:
方法一:采用递归的解法,拆分成2部分
1、将第3个节点开始的链表作为下一次递归的参数,用它去继续交换。
2、将第1个节点指向递归返回的结果,将第2个节点重新指向第1个节点,并返回它,这是新的head。
class Solution {
public:
ListNode* swapPairs(ListNode* head)
{
if ( head == NULL || head->next== NULL) return head;
ListNode *newhd = head->next;
head->next = swapPairs(newhd->next);
newhd->next = head;
return newhd;
}
};
方法二:采用循环的解法,依次交换相邻的两个节点
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode *newHead = new ListNode(-1);
newHead->next = head;
for (ListNode *p1 = newHead, *p2 = head; p2 && p2->next; p1 = p2, p2 = p2->next)
{
p1->next = p2->next;
p2->next = p1->next->next;
p1->next->next = p2;
}
return newHead->next;
}
};