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

LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)

2015-01-04 10:15 351 查看

题目:

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.
给定一个链表,交换每相邻两个结点的位置,返回头结点。
空间复杂度:O(1)。不能改变链表结点的值,只能改变链表结点。

思路:

直接看代码。

代码:

/**
* 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)
return head;
ListNode *p1=head,*p2=p1->next,*tmp=head;
while(p2)
{
if(p1 == head)
head = p2;
tmp = p2->next;

if(p2->next)
{
//如果p2后还有两个结点
if(p2->next->next)
{
p1->next = p2->next->next;
p2->next = p1;
p2 = p1->next ;
p1 = tmp;
}
//p2后只有一个结点
else
{
p1->next = p2->next;
p2->next = p1;
break;
}
}
//p2后没有结点了
else
{
p2->next = p1;
p1->next = NULL;
break;
}

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