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)
  • 相关阅读:
    JAVA 框架
    npm安装超时,使用淘宝镜像
    使用vite搭建Vue3项目
    前端常用框架
    vue发布自己的组件库-vue3
    vue2升级vue3-基础教程
    Navicat Premium 15破解失败解决方案
    大屏
    vue使用高德地图
    vue生命周期及钩子函数
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9746036.html
Copyright © 2011-2022 走看看