zoukankan      html  css  js  c++  java
  • 0024. Swap Nodes in Pairs (M)

    Swap Nodes in Pairs (M)

    题目

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

    You may not modify the values in the list's nodes, only nodes itself may be changed.

    Example:

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

    题意

    按顺序将给定的链表中的元素两两交换,但不能更改结点中的值,只能对结点本身进行操作。

    思路

    问题中包含链表和子结点等概念,且结点需要变动,很容易想到利用递归来解决,直接上代码。

    或者直接将结点拆下放到新链表中更简单。


    代码实现

    Java

    class Solution {
        public ListNode swapPairs(ListNode head) {
            // 递归边界,当待交换结点数不足2时直接返回
            if (head == null || head.next == null) {
                return head;
            }
            ListNode first = head;
            ListNode second = first.next;
            first.next = swapPairs(second.next);
            second.next = first;
            return second;
        }
    }
    

    JavaScript

    新链表

    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var swapPairs = function (head) {
      let dummy = new ListNode()
      let cur = dummy
    
      while (head !== null) {
        let a = head, b = head.next
        if (b !== null) {
          head = b.next
          b.next = a
          a.next = null
          cur.next = b
          cur = a
        } else {
          cur.next = a
          head = null
        }
      }
    
      return dummy.next
    }
    

    递归

    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var swapPairs = function (head) {
      if (head === null) {
        return null
      }
    
      if (head.next !== null) {
        let nextHead = swapPairs(head.next.next)
        head.next.next = head
        head = head.next
        head.next.next = nextHead
      }
    
      return head
    }
    
  • 相关阅读:
    查看docker程序使用的内存脚本
    shell分割字符串并赋值给变量
    【Ceph】Ceph学习理解Ceph的三种存储接口:块设备、文件系统、对象存储
    删除软连接导致源文件一起被删除
    nginx+keepalived实现双活
    maven私有仓库的搭建
    直接访问nginx ip地址返回404错误
    Solaris基础系列之四:图解Oracle 10g安装
    数据库进阶系列之一:漫谈数据库索引
    Tips&Tricks系列四:C#面试笔试小贴士
  • 原文地址:https://www.cnblogs.com/mapoos/p/13175022.html
Copyright © 2011-2022 走看看