zoukankan      html  css  js  c++  java
  • LeetCode——两两交换链表中的节点

    Q:将给定的链表中每两个相邻的节点交换一次,返回链表的头指针
    例如,
    给出1->2->3->4,你应该返回链表2->1->4->3。
    你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。
    A:

        public static ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null)
                return head;
            ListNode head0 = new ListNode(Integer.MIN_VALUE);
            head0.next = head;
            ListNode curr = head0;
            while (curr.next != null && curr.next.next != null) {
                curr.next = swap(curr.next,curr.next.next);//这里分开写看的清楚
                curr = curr.next.next;
            }
            return head0.next;
        }
    
        private static ListNode swap(ListNode node1, ListNode node2) {
            node1.next = node2.next;
            node2.next = node1;
            return node2;
        }
    
    
  • 相关阅读:
    ajax简单案例
    jquery中的数据传输
    java-Reflect
    Factory Method 和AbstractFactory
    Singleton
    英语六级口语备考指南
    ACM信息汇总
    jquery练习
    char可不可以存汉字
    信息安全
  • 原文地址:https://www.cnblogs.com/xym4869/p/12642262.html
Copyright © 2011-2022 走看看