LeetCode24-Swap Nodes in Pairs

Description

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:

Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.

Mind Path

Note1: Using only constant extra space means that we can't use recusive solutions. Note2: Not modifying the values means that we can only swap nodes to do the swap.

Solution

package com.dylan.leetcode;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;

/**
 * Created by liufengquan on 2018/8/11.
 */
public class SwapNodesInPairs {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = new ListNode(0);
        ListNode temp = newHead;
        temp.next = head;
        while (head != null && head.next != null) {
            temp.next = head.next;
            ListNode next = head.next.next;
            temp.next.next = head;
            head = next;
            temp = temp.next.next;
            temp.next = head;
        }
        return newHead.next;
    }

    @Test
    public void testSwapSwapPairs() {
        ListNode listNode = init(1);
        Assert.assertEquals(listNode, swapPairs(listNode));

        ListNode second = init(2);

        ListNode swapped = swapPairs(second);
        Assert.assertEquals(1, swapped.val);
        Assert.assertEquals(0, swapped.next.val);

        ListNode third = init(3);
        ListNode thirdSwap = swapPairs(third);
        Assert.assertEquals(1, thirdSwap.val);
        Assert.assertEquals(0, thirdSwap.next.val);
        Assert.assertEquals(2, thirdSwap.next.next.val);
    }

    public ListNode init(int n) {
        ListNode head = new ListNode(1);

        ListNode temp = head;
        for (int i = 0; i < n; i++) {
            temp.next = new ListNode(i);
            temp = temp.next;
        }

        return head.next;
    }
}

转载于:https://my.oschina.net/liufq/blog/1926332

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值