码迷,mamicode.com
首页 > 其他好文 > 详细

分类解决问题的思想

时间:2017-11-01 00:05:27      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:break   第一个   linked   auto   分类   lin   nbsp   class   swap   

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;
}
};

分类解决问题的思想

标签:break   第一个   linked   auto   分类   lin   nbsp   class   swap   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!