题解 | #重排链表#
重排链表
http://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b
import java.util.HashMap;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if (null == head) {
return;
}
HashMap<ListNode, ListNode> hashMap = new HashMap<>(); // 定义一个 HashMap,用于存放每个节点与其前一个节点的对应关系
ListNode leftNode = head;
ListNode rightNode = head;
ListNode tmpNode = head; // 定义一个辅助指针
int len = 1; // 定义一个整型变量,用于存放链表的长度
hashMap.put(head, null);
while (null != tmpNode.next) {
hashMap.put(tmpNode.next, tmpNode);
tmpNode = tmpNode.next;
len++;
}
// 循环结束时,tmpNode 指向链表的末尾
rightNode = tmpNode;
for (int i = 1; i <= len - 1; i++) {
if (i % 2 != 0) { // 当前 i 为奇数时
tmpNode = leftNode.next;
leftNode.next = rightNode;
leftNode = tmpNode;
if (i == len - 1) {
leftNode.next = null;
}
}
else { // 当前 i 为偶数时
tmpNode = hashMap.get(rightNode);
rightNode.next = leftNode;
rightNode = tmpNode;
if (i == len - 1) {
rightNode.next = null;
}
}
}
return;
}
}