zoukankan      html  css  js  c++  java
  • 24. 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.

    AC code:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode **dummy = &head, *a, *b;
            while ((a=*dummy) && (b=a->next)) {
                a->next = b->next;
                b->next = a;
                *dummy = b;
                dummy = &(a->next);
            }
            return head;
        }
    };
    

    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Swap Nodes in Pairs.

      

    1 2 3 4 5 6 
    a       
      b   
      3 1                                                                          
     *pp 
                        pp->2->1->
      a b                  (b)(a)
        4 3                   *pp 
       *pp 
                               pp->4->3->
        a b                       (b)(a)
          5 4                        *pp 
         *pp
                                     pp->6->5
          a b                           (b)(a)
            6 5                            *pp 
             *pp 
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Web 服务器配置
    Web 浏览
    C++ Web 编程
    C++ 多线程
    C++ 信号处理
    C++ 预处理器
    C++ 模板
    C++ 命名空间
    C++ 动态内存
    C++ 异常处理
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9746036.html
Copyright © 2011-2022 走看看