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;
}
};
相关文章推荐
- Leetcode刷题记——24. Swap Nodes in Pairs(交换成对结点)
- 【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- [Leetcode] Swap nodes in pairs 成对交换结点
- LeetCode OJ:Swap Nodes in Pairs(成对交换节点)
- [LeetCode] Swap Nodes in Pairs 成对交换节点
- [LeetCode]Swap Nodes in Pairs 成对交换
- Swap Nodes in Pairs:交换链表数组相邻元素的值
- Swap Nodes in Pairs --成对交换链表节点(重重重)
- LeetCode 24. Swap Nodes in Pairs(按对交换单链表结点)
- Leet Code 24 Swap Nodes in Pairs - 成对交换节点 - Java
- [LeetCode]Swap Nodes in Pairs 成对交换
- LeetCode - 24 - Swap Nodes in Pairs(交换链表结点)
- [C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)
- Swap Nodes in Pairs(交换一对结点)
- 交换单链表中相邻的两个元素 Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs(成对交换节点)
- [LeetCode] 24. Swap Nodes in Pairs 成对交换节点