zoukankan      html  css  js  c++  java
  • 分类解决问题的思想

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

  • 相关阅读:
    团队项目-个人博客-4.25
    团队项目-个人博客-4.24 学习进度08
    评价使用的输入法
    个人工作总结08
    个人工作总结07
    第八周学习进度条
    个人工作总结06
    构建之法阅读笔记04
    个人工作总结05
    个人工作总结04
  • 原文地址:https://www.cnblogs.com/fenglongyu/p/7764328.html
Copyright © 2011-2022 走看看