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
    }
    
  • 相关阅读:
    两个时间相差多少
    JqGrid中文文档
    将A标签的href用iframe打开(JS)
    GridView 自动生成列 没有整理.
    母板页引用JS的办法
    js 判断 文本框是否被全选 ..
    jQuery 调用 Web Services 。。
    WINDOWS 7 + VS2008 +MSSQL 2005 安装成功!
    C# Serializable 的示例
    Microsoft.Crm.WebServices.Crm2007.MultipleOrganizationSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Versi
  • 原文地址:https://www.cnblogs.com/mapoos/p/13175022.html
Copyright © 2011-2022 走看看