问题描述:
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) {
if(head == NULL || head->next == NULL) return head;
ListNode *grandChild = swapPairs(head->next->next);
ListNode *Child = head->next;
head->next = grandChild;
Child->next = head;
return Child;
}
};
/**
* 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) {
if(head == NULL || head->next == NULL){
return head;
}
ListNode* newHead = new ListNode(0);
newHead->next = head;
ListNode* preNode = newHead;
ListNode* curNode = head;
while(curNode != NULL && curNode->next != NULL)
{
// swap curNode and curNode->next
preNode->next = curNode->next;
curNode->next = preNode->next->next;
preNode->next->next = curNode; //此处我写成 curNode = preNode->next->next, 编译不通过,对链表的操作还是有些不清楚
// go over two nodes
preNode = curNode;
curNode = curNode->next;
}
head = newHead->next;
delete newHead;
return head;
}
};