zoukankan      html  css  js  c++  java
  • 24. Swap Nodes in Pairs

    一、题目

      1、审题

        

      2、分析:

        依次交换相邻两个结点,其中每个结点只交换一次。

    二、解答

      1、思路:

        方法一:直接交换两个结点,其中交换方式为先删除结点 n 后一个结点,再将删除的结点在 n 结点之前插入。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode swapPairs(ListNode head) {
    
            ListNode pre = new ListNode(0);
            ListNode dummy = head;
            ListNode pig = pre;
            pre.next = dummy;
    
            while(dummy != null && dummy.next != null) {
    
                ListNode next = dummy.next;
                dummy.next = next.next; // 删除
    
                pre.next = next;        // 插入
                next.next = dummy;
    
                pre = dummy;
                dummy = dummy.next;
    
            }
    
            return pig.next;
        }
    }

      方法二: 直接交换两个相邻结点的值,而不用交换结点。

      

    public class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode resultHead = head;
            int tempVal;
            while(head != null && head.next != null) {
                // swap
                tempVal = head.next.val;
                head.next.val = head.val;
                head.val = tempVal;
                
                // 
                head = head.next.next;
            }
            return resultHead; 
        }
    }
  • 相关阅读:
    cts 测试环境安装 ubuntu
    关于JS中乘除法的浮点错误解决方法
    事件移除匿名函数
    获取元素offsetLeft值
    jquery on and bind different
    获取事件相对于文档的位置
    angular 使用过程中遇到的问题
    python_文件操作
    monkerunner
    monkey_使用_脚本编写
  • 原文地址:https://www.cnblogs.com/skillking/p/9420220.html
Copyright © 2011-2022 走看看