zoukankan      html  css  js  c++  java
  • Swap Nodes in Pairs(交换节点)

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

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

    Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

    两两交换节点。

    1、使用递归,简单,空间不是固定的O(n)。

     public ListNode swapPairs(ListNode head) {
            if(head == null||head.next==null) return head;
            //递归,但是空间O(n)
            ListNode node=head.next;
            head.next=swapPairs(head.next.next);
            node.next=head;
            return node;
            
    }

    2、直接遍历修改。。两个一组操作。因为头结点也会变,所以需要额外添加头结点。

     //非递归
            ListNode dummy=new ListNode(0);
            dummy.next=head;
            ListNode current=dummy;
            //最后如果只剩一个节点,不用交换,本身就在current上所以不作处理
            while(current.next!=null&&current.next.next!=null){
                ListNode first=current.next;
                ListNode second=current.next.next;
                first.next=second.next;
                current.next=second;
                current.next.next=first;
                current=current.next.next;
            }
            return dummy.next;
  • 相关阅读:
    BZOJ 3991 set维护dfs序
    BZOJ 4547 矩阵快速幂
    WERTYU | TEX Quotes
    高精度运算
    最大公约数和最小公倍数
    老鼠的旅行
    数据交换
    1136 A Delayed Palindrome
    1137 Final Grading
    1138 Postorder Traversal
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8111343.html
Copyright © 2011-2022 走看看