zoukankan      html  css  js  c++  java
  • LeetCode:24. Swap Nodes in Pairs(Medium)

    1. 原题链接

    https://leetcode.com/problems/swap-nodes-in-pairs/description/

    2. 题目要求

    给定一个链表,交换相邻的两个结点。已经交换的结点,不再进行交换。

    注意:所使用的空间大小固定

    例如,1->2->3->4转换后为2->1->4->3

    3. 题目思路

    使用一个遍历指针current和两个辅助指针first、second,first保存current指针所在结点的后继结点,second保存current指针所在结点的后继的后继结点。

    令first的后继指向second的后继,current的后继等于second,current后继的后继等于first,current等于first

    4. 代码实现

    public class SwapNodeInPairs24 {
        public static void main(String[] args) {
            ListNode l1 = new ListNode(1);
            ListNode l2 = new ListNode(2);
            ListNode l3 = new ListNode(3);
            ListNode l4 = new ListNode(4);
            ListNode l5 = new ListNode(5);
            ListNode l6 = new ListNode(6);
            l1.next = l2;
            l2.next = l3;
            l3.next = l4;
            l4.next = l5;
            l5.next = l6;
    
            ListNode ls1 = l1;
            while (ls1 != null) {
                System.out.print(ls1.val);
                ls1 = ls1.next;
            }
            System.out.println("");
    
            ListNode ls2 = swapPairs(l1);
            while (ls2 != null) {
                System.out.print(ls2.val);
                ls2 = ls2.next;
            }
    
        }
    
        public static ListNode swapPairs(ListNode head) {
            ListNode headPointer = new ListNode(0);
            headPointer.next = head;
            ListNode current = headPointer;
    
            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 = first;
            }
    
    
            return headPointer.next;
        }
    
        public static class ListNode {
            int val;
            ListNode next;
    
            ListNode(int x) {
                val = x;
            }
        }
    }
    

      

  • 相关阅读:
    SQL 查询两个时间段是否有交集的情况 三种写法
    c# 时间区间求并集
    uniapp 身份证识别 微信 百度 图片前端压缩 图片后端压缩
    Git命令大全
    构建android studio项目
    如何查tomcat进程和杀死进程
    mysql 备份 还原不了
    解决git extensions每次要输入用户名和密码
    JS string 转 Byte64[]
    Git cmd
  • 原文地址:https://www.cnblogs.com/huiAlex/p/8134126.html
Copyright © 2011-2022 走看看