菜鸟刷leetcode 24. Swap Nodes in Pairs
2016-11-11 15:50
190 查看
自己写的时候,想到了交换的方法,但是没有想到前面的点没有前继,导致[1 2 3 4 5]只出现结果[1 3 5]。当时是这样写的:
while()
{
p=head->next;
head->next=p->next;
p->next=head;
head=p->next->next;
}
由于p前面没有数据,导致消失。应该加一个前继,不然链表断了。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy(0),*pre=&dummy,*left(nullptr),*right(nullptr);
dummy.next=head;
while(pre!=NULL&&pre->next!=NULL&&pre->next->next!=NULL)
{
left=pre->next;
right=left->next;
left->next=right->next;
pre->next=right;
right->next=left;
pre=pre->next->next;
}
return dummy.next;
}
};
while()
{
p=head->next;
head->next=p->next;
p->next=head;
head=p->next->next;
}
由于p前面没有数据,导致消失。应该加一个前继,不然链表断了。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy(0),*pre=&dummy,*left(nullptr),*right(nullptr);
dummy.next=head;
while(pre!=NULL&&pre->next!=NULL&&pre->next->next!=NULL)
{
left=pre->next;
right=left->next;
left->next=right->next;
pre->next=right;
right->next=left;
pre=pre->next->next;
}
return dummy.next;
}
};
相关文章推荐
- leetcode 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode Python
- leetcode 24. Swap Nodes in Pairs
- LeetCode --- 24. Swap Nodes in Pairs
- leetcode_24. Swap Nodes in Pairs C++
- **LeetCode 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- <LeetCode OJ> 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- 24.[Leetcode]Swap Nodes in Pairs
- Leetcode ☞ 24. Swap Nodes in Pairs ☆
- leetcode 24. Swap Nodes in Pairs(链表)
- LeetCode *** 24. Swap Nodes in Pairs
- (Java)LeetCode-24. Swap Nodes in Pairs
- [leetcode] 24. Swap Nodes in Pairs 解题报告
- LeetCode 24. Swap Nodes in Pairs 解题报告
- leetcode 24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- Leetcode 24. Swap Nodes in Pairs (Easy) (cpp)
- [leetcode] 【链表】24. Swap Nodes in Pairs