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

  • 相关阅读:
    BZOJ1051:受欢迎的牛(并查集 / Tarjan)
    ZOJ3261:Connections in Galaxy War(逆向并查集)
    POJ2912:Rochambeau(带权并查集)
    POJ1308:Is It A Tree?(并查集)
    RBAC权限管理
    RBAC权限管理
    用户密码加密简介
    用户密码加密简介
    Java文件路径
    Java文件路径
  • 原文地址:https://www.cnblogs.com/fenglongyu/p/7764328.html
Copyright © 2011-2022 走看看