zoukankan      html  css  js  c++  java
  • 【Leetcode】24. 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.

    Tips:给定一个链表,在不改变链表的值,只改变结点的指针的情况下完成相邻两个结点的交换。

    如:Input:1->2->3->4

      Output:2->1->4->3

    思路:设置两个指针,first second,分别为当前指针的next以及next.next

    first.next指向second.next;(1->3)

    然后将second.next指向first(2->1)。

    再将当前指针后移:cur.next=second; cur = first;

    package medium;
    
    import dataStructure.ListNode;
    
    public class L24SwapNodesInPairs {
    
        public ListNode swapPairs(ListNode head) {
            if (head == null)
                return head;
            ListNode node = new ListNode(0);
            node.next = head;
            ListNode cur = node;
            
            while (cur.next != null && cur.next.next!=null) {
                ListNode first = cur.next;
                ListNode second = cur.next.next;
                first.next = second.next;//1->3
                second.next=first;//2->1->3
                cur.next=second;
                cur = first;
            }
            return node.next;
    
        }
    
        public static void main(String[] args) {
            ListNode head1 = new ListNode(1);
            ListNode head2 = new ListNode(2);
            ListNode head3 = new ListNode(3);
            ListNode head4 = new ListNode(4);
            ListNode head5 = new ListNode(5);
            ListNode head6 = new ListNode(6);
            ListNode head7 = null;
            head1.next = head2;
            head2.next = head3;
            head3.next = head4;
            head4.next = head5;
            head5.next = head6;
            head6.next = head7;
            L24SwapNodesInPairs l24 = new L24SwapNodesInPairs();
            ListNode head = l24.swapPairs(head1);
            while (head != null ) {
                System.out.println(head.val);
                head=head.next;
            }
        }
    }
  • 相关阅读:
    P2018 消息传递[dp]
    P1436 棋盘分割[dp]
    一条线段引发的思考
    浅谈树上差分
    P2680 运输计划[二分+LCA+树上差分]
    P1600 天天爱跑步[桶+LCA+树上差分]
    P4560 [IOI2014]Wall 砖墙
    P1311 选择客栈[模拟]
    P1314 聪明的质监员[二分答案]
    Linux snmp导入MIB库
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8447786.html
Copyright © 2011-2022 走看看