Leetcode——24. Swap Nodes in Pairs
2017-12-26 13:35
337 查看
分四种情况讨论:有0个,1个,2个和大于2个结点。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL)//0或1个结点
return head;
ListNode *p=head,*q=head;
ListNode *headnext=head->next;
ListNode *tmp=p->next;
p->next=p->next->next;
tmp->next=p;
p=p->next;
if(p==NULL) return headnext;//2个结点
while (p->next!=NULL)//大于2个结点
{
ListNode *tmp=p->next;
p->next=p->next->next;
tmp->next=p;
q->next=tmp;
q=p;
p=p->next;
if(p==NULL)
break;
}
return headnext;
}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL)//0或1个结点
return head;
ListNode *p=head,*q=head;
ListNode *headnext=head->next;
ListNode *tmp=p->next;
p->next=p->next->next;
tmp->next=p;
p=p->next;
if(p==NULL) return headnext;//2个结点
while (p->next!=NULL)//大于2个结点
{
ListNode *tmp=p->next;
p->next=p->next->next;
tmp->next=p;
q->next=tmp;
q=p;
p=p->next;
if(p==NULL)
break;
}
return headnext;
}
};
相关文章推荐
- LeetCode 24. Swap Nodes in Pairs(交换节点)
- LeetCode-24. Swap Nodes in Pairs-Attemped using C
- <LeetCode OJ> 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
- 【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素
- leetcode: 24. Swap Nodes in Pairs
- [leetcode: Python]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 成对交换节点
- [LeetCode]24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs ---java