zoukankan      html  css  js  c++  java
  • leetcode24,交换链表相邻的节点

    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.

    对于这样链表交换的题目,我一般都有两种解法。

    第一种,看链表每个节点带有的数据量,这道题带有只有一个value值,只有一个int值,所以我一开始的想法就是,不真实的交换节点,只是交换里面的数据。

    这样的好处是空间复杂度特别省,适合那些每个节点数据很少,要求不高的链表交换。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next == null)
                return head;
            
            ListNode A = head;
            ListNode B = head.next;
            
            int t;
            while(A != null && B != null){
                t = B.val;
                B.val = A.val;
                A.val = t;
                
                if(B.next == null)
                    break;
                A = B.next;
                B = B.next.next;
            }
            
            return head;
        }
    }

    第二种解法就是真的去交换节点。

    那么就需要多余的节点去记录当前结点的情况然后去交换

    我用h,1,2,3这4个节点来说明。

    123是原来的节点。

    而h是头节点,指向1

    下面是交换的步骤。

    h->1->2->3

    1->3(这个3通过2.next找)

    h->2(这个直接有2)

    h->->1(这个1也是直接有)

    h->3(这个3通过1.next找)

    image

  • 相关阅读:
    控制器生命周期逻辑调用
    数据持久化
    Mac屏幕录制Gif
    iOS开发应用上架必读最新苹果审核规则
    过滤字符串中的非汉字、字母、数字
    文字加描边
    博客全局修改需求
    iOS Xcode12 运行iOS15系统程序卡在启动页要等很久才能进入主页
    macOS环境:安装Go(21-10-22完)
    关闭WIN10自动配置 IPV4 地址 169.254解决方法
  • 原文地址:https://www.cnblogs.com/linkstar/p/5979227.html
Copyright © 2011-2022 走看看