您的位置:首页 > Web前端 > Node.js

Swap Nodes in Pairs

2015-10-12 23:18 525 查看
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.

给定一个链表,把相邻两个结点调换位置;返回head

Java代码:

package com.rust.cal;

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class SwapNodesinPairs {
public static ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
//必须先判断head是否为null,否则会出java.lang.NullPointerException
//如果输入的head == null,先判断head.next会找不到目标
return head;
}
/* 针对前两个结点 */
ListNode pre = head.next, later, veryFirst;
head.next = pre.next;
pre.next = head;
head = pre;
later = head.next;
/*
* 针对后续结点
* 连续有2个结点,才进行换位
*/
while (later.next != null && later.next.next != null) {
veryFirst = later;
pre = pre.next.next;
later = later.next.next;
pre.next = later.next;
later.next = pre;
veryFirst.next = later;
later = pre;
pre = veryFirst.next;
}
return head;
}

public static void main(String args[]){
/*
* prepare data
*/
ListNode head = new ListNode(1);
ListNode initHead = head;
for (int i = 2; i < 10; i++) {
initHead.next = new ListNode(i);
initHead = initHead.next;
}

head = swapPairs(head);
/*
* show data
*/
ListNode newHead = head;
while(newHead != null){
System.out.print(newHead.val + "  ");
newHead = newHead.next;
}
ListNode nothing = new ListNode(1);
swapPairs(nothing.next);
}
}


输出:

2 1 4 3 6 5 8 7 9

这个方法是先处理前2个结点,再循环处理后续的结点。其实结点的处理方法都差不多,在LeetCode讨论区看到递归解法,搬运过来

Java代码:

public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;

ListNode n1 = head;
ListNode n2 = head.next;

n1.next = n2.next;
n2.next = n1;

n1.next = swapPairs(n1.next);

return n2;
}


利用方法开头对head是否为null的判断作为递归的条件,比第一个方法优雅很多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: