题目:
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.
思路:
链表依次交换,道理很简单,关键是细心。
代码:
/**
* 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) {
ListNode* newTail = new ListNode(0);
ListNode* newPtr = newTail;
ListNode* ptr = head;
while(ptr != NULL){
if(ptr->next == NULL){
newPtr->next = ptr;
break;
}
else{
ListNode* tmp = ptr->next->next;
newPtr->next = ptr->next;
newPtr = newPtr->next;
newPtr->next = ptr;
newPtr = newPtr->next;
newPtr->next = NULL;
ptr = tmp;
}
}
return newTail->next;
}
};
仔细观察如上的代码,我们会发现其实我们可以用一个递归的方式来简单实现该代码。
/**
* 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) {
ListNode* p = head;
ListNode* begin = NULL;
if(p == NULL)
{
return NULL;
}
if(p->next != NULL)
{
ListNode* t = p;
p = p->next;
t->next = p->next;
p->next = t;
if(begin == NULL)
{
begin = p;
}
p = p->next;
}
else
{
return head;
}
p->next = swapPairs(p->next);
return begin;
}
};