首页 > 其他 > 详细

分类解决问题的思想

时间:2017-10-31 23:05:51      阅读:209      评论:0      收藏:0      [点我收藏+]

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.

此题解决分为几个步骤,(整个问题的特殊解如:head==nulptr,head->next==nullptr)第一个一般性结点的解决,第二个特殊结点的解决(仔细分好),第三遍历所有的问题集

分类的思想应用=== 

然后在尾部情况应用break;跳出尾循环会减少对while的结束要求复杂度

class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == nullptr)return head;
if(head->next==nullptr)return head;
auto res = head->next;
while(head->next!=nullptr&&head!=nullptr)
{
auto headA = head;
if(head->next->next==nullptr){swapThree(headA);break;}
else if(head->next->next->next==nullptr){swapOne(headA);break;}
else{
head = head->next->next;
swapTwo(headA);
}
}
return res;
}
void swapOne(ListNode* H)
{
auto mark = H->next->next;
H->next->next = H;
H->next = mark;
mark->next = nullptr;
}
void swapTwo(ListNode* H)
{
auto mark = H->next->next;
H->next->next = H;
H->next = mark->next;
}
void swapThree(ListNode* H)
{
H->next->next = H;
H->next = nullptr;
}
};

分类解决问题的思想

原文:http://www.cnblogs.com/fenglongyu/p/7764328.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!