码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】24. Swap Nodes in Pairs

时间:2018-02-14 01:00:41      阅读:47      评论:0      收藏:0      [点我收藏+]

标签:style   may   string   change   package   tput   ati   span   stat   

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;
        }
    }
}

 

【Leetcode】24. Swap Nodes in Pairs

标签:style   may   string   change   package   tput   ati   span   stat   

原文地址:https://www.cnblogs.com/yumiaomiao/p/8447786.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!