leetcode143. 重排链表
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reorder-list
题目要描述
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例1:
输入:head = [1,2,3,4]
输出:[1,4,2,3]
示例2:
输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]
提示:
链表的长度范围为 [1, 5 * 1000]
1 <= node.val <= 1000
解题思路
先找到链表中间节点.
然后把剩下的一半的节点加到Stack 队列.根据先进后出的原理,
会先弹出最后节点.
然后和前面的节点进行指针重连.
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null){
return;
}
ListNode Lmid = getMid(head);
//中间节点的后半段链表拿到
ListNode rMid = Lmid.next;
//指针指向null
Lmid.next = null;
Stack<ListNode> stack = getStack(rMid);
ListNode cur = head;
ListNode next = null;
while(!stack.isEmpty()){
ListNode last = stack.pop();
next = cur.next;
cur.next = last;
last.next = next;
cur = next;
}
}
/**
* 获取链表的中间节点,偶数长度返回中间上节点
*/
public ListNode getMid(ListNode head){
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
/**
* 把链表的后半段 加进队列中
*/
public Stack<ListNode> getStack(ListNode slow){
Stack<ListNode> stack = new Stack<>();
while(slow != null){
stack.push(slow);
slow = slow.next;
}
return stack;
}
}