zoukankan      html  css  js  c++  java
  • Swap Nodes in Pairs

    Given a linked list, swap every two adjacent nodes and return its head.

    Example:

    Given 1->2->3->4, you should return the list as 2->1->4->3.

    Note:

    • Your algorithm should use only constant extra space.
    • You may not modify the values in the list's nodes, only nodes itself may be changed.
    class Solution{
        public:
            ListNode* swapPairs(ListNode* head){
                ListNode *dummy = new ListNode(-1);
                ListNode *pre = dummy;
                
                dummy->next = head;
                while(pre->next && pre->next->next){
                    ListNode *t = pre->next->next;
                    pre->next->next = t->next;
                    t->next = pre->next;
                    pre->next = t;
                    pre = t->next;  
                }
                return dummy->next;
            }
    };
    
    //递归写法稍微有些复杂
    class Solution{
        public:
            ListNode* swapPairs(ListNode* head){
                if(!head || !head->next) return head;
                ListNode *t = head->next;
                head->next = swapPairs(head->next->next);
                t->next = head;
                return t;
            }
    };
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    nginx启动
    java中有三种移位运算符
    easyUI属性汇总
    rose学习
    eclipse 启动到load workbench 后静止
    nvl函数
    Io 异常: Socket closed
    编译错误和运行时错误
    java 二进制编码
    MyFormat 幫助類
  • 原文地址:https://www.cnblogs.com/hujianglang/p/11415658.html
Copyright © 2011-2022 走看看