24. 两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:
- 你的算法只能使用常数的额外空间。
- 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
一、分析
图示:
规律:
- 交换过程基本就是:
previous.next = pair1.next;
pair1.next = pair2.next;
pair2.next = pair1;
- 注意处理链表头部,
previous
为null
的情况 - 注意处理链表尾部,
after
为null
的情况 - 其余就是一对对的遍历链表即可
二、解答
/**
* Copyright © 2018 by afei. All rights reserved.
*
* @author: afei
* @date: 2018年11月19日
*/
public class Solution {
public static void main(String[] args) {
// create a list
ListNode head = null;
ListNode tail = null;
for (int i = 1; i <= 20; i++) {
ListNode node = new ListNode(i);
if (head == null) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
}
// do swap
head = swapPairs(head);
// print list
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
public static ListNode swapPairs(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
// init
ListNode result = head.next;
ListNode pair1 = head;
ListNode pair2 = head.next;
ListNode previous = null;
// swap
pair1.next = pair2.next;
pair2.next = pair1;
previous = pair1;
pair1 = pair1.next;
while (pair1 != null) {
pair2 = pair1.next;
if (pair2 == null) {
break;
}
// swap
previous.next = pair2;
pair1.next = pair2.next;
pair2.next = pair1;
previous = pair1;
pair1 = pair1.next;
}
return result;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}
三、项目地址
https://github.com/afei-cn/LeetCode/tree/master/24.%20Swap%20Nodes%20In%20Pairs