题目描述
一看题目反序:用栈 更新:O(1) 空间复杂度
思路 & 代码
先快慢指针,找到需要入栈的起点,然后逐个入栈 然后逐个出栈,进行重排即可 注意1:记得对重排后的链表结尾进行 Last.next = null 处理,防止成环 注意2:奇偶情况要进行处理,可见代码注释 时间复杂度 O(n) ,空间复杂度 O(n)
class Solution {
public void reorderList ( ListNode head) {
ListNode now = head;
now = head;
ListNode pre = head;
while ( now. next != null && now. next. next != null ) {
pre = pre. next;
now = now. next. next;
}
if ( now. next != null ) {
pre = pre. next;
}
now = pre. next;
pre. next = null ;
Stack < ListNode > myStack = new Stack < > ( ) ;
while ( now != null ) {
myStack. push ( now) ;
now = now. next;
}
now = head;
while ( ! myStack. isEmpty ( ) ) {
ListNode temp = myStack. pop ( ) ;
ListNode nextLoop = now. next;
temp. next = now. next;
now. next = temp;
now = nextLoop;
}
}
}
更新版:快慢指针 + 翻转链表
class Solution {
public void reorderList ( ListNode head) {
if ( head == null || head. next == null ) {
return ;
}
ListNode slow = head, fast = head;
ListNode slowPre = null ;
while ( fast != null && fast. next != null ) {
slowPre = slow;
slow = slow. next;
fast = fast. next. next;
}
if ( fast != null ) {
slowPre = slow;
slow = slow. next;
}
slowPre. next = null ;
ListNode pre = null ;
while ( slow != null ) {
ListNode nextNode = slow. next;
slow. next = pre;
pre = slow;
slow = nextNode;
}
fast = head;
while ( pre != null ) {
ListNode temp1 = fast. next;
ListNode temp2 = pre. next;
fast. next = pre;
pre. next = temp1;
fast = temp1;
pre = temp2;
}
}
}