Leetcode24. Swap Nodes in Pairs

Posted 于淼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode24. 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;
        }
    }
}

 


以上是关于Leetcode24. Swap Nodes in Pairs的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-24 Swap Nodes in Pairs

LeetCode 24 Swap Nodes in Pairs

Leetcode24. Swap Nodes in Pairs

Leetcode24. Swap Nodes in Pairs

Leetcode 24——Swap Nodes in Pairs

leetcode24 Swap Nodes in Pairs