Skip to content

Commit d677146

Browse files
committed
Update solution/0024.Swap Nodes in Pairs/Solution2.cpp
add 0024 cpp (non-recursion 4ms)version
1 parent 63be737 commit d677146

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// 非递归版本
2+
/**
3+
* Definition for singly-linked list.
4+
* struct ListNode {
5+
* int val;
6+
* ListNode *next;
7+
* ListNode(int x) : val(x), next(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
ListNode* swapPairs(ListNode* head) {
13+
ListNode *pPre, *p1, *p2 ;
14+
// 建立一个头结点就不用特殊处理第一个工作节点了
15+
ListNode node(0) ;
16+
node.next = head ;
17+
p2 = &node ;
18+
19+
while ( (pPre = p2)
20+
&& (p1 = pPre->next)
21+
&& (p2 = p1->next) )
22+
{
23+
pPre->next = p2 ;
24+
p1->next = p2->next ;
25+
p2->next = p1 ;
26+
swap(p1, p2) ; // p1、p2 实质上已经交换了位置,所以指针也要交换一下以保证循环条件顺序
27+
}
28+
29+
return node.next ;
30+
}
31+
};

0 commit comments

Comments
 (0)