您的位置:首页 > Web前端 > Node.js

【leetCode】Swap Nodes in Pairs

2015-08-01 16:06 387 查看
题目:

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* newHead = NULL;
ListNode* frontNode = NULL;
ListNode* midNode = NULL;
ListNode* rearNode = NULL;
if (head == NULL)
return NULL;
//如果只有Head结点,就直接返回Head结点了
if (head->next == NULL)
return head;
frontNode = head->next;
rearNode = head;
//暂存结点,保存rearNode前面的一个node
ListNode* parent = new ListNode(0);
parent->next = rearNode;
//如果链表只有两个结点
if (frontNode->next == NULL)
{
//完成两个结点的交换
rearNode->next = frontNode->next;
frontNode->next = rearNode;
parent->next = frontNode;
return frontNode;
}
//如果链表有不止两个结点
while (rearNode!= NULL && frontNode != NULL)
{
//完成两个结点的交换
rearNode->next = frontNode->next;
frontNode->next = rearNode;
parent->next = frontNode;
//如果head == rearNode,说明这是链表刚开始,要记录下链表头
if (head == rearNode)
head = frontNode;
//如果后面还存在两个(及以上)的结点,就向后移动
if (rearNode->next != NULL && rearNode->next->next != NULL)
{
parent = rearNode;
rearNode = rearNode->next;
frontNode = rearNode->next;
}
else
break;
}
return head;
}
};


收工~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: