题目:
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
思路:网上找的大神的代码,原文链接:https://blog.csdn.net/mine_song/article/details/71762350
题目中的要求有点不懂,实际的节点交换就是不能只简单改变节点的值
以下代码的基本思想是首先找到链表中间的节点,将链表分成两部分,然后对后一半的链表进行反转,最后将两个链表合并起来。
我自己重写了代码,发现问题出在变量写错,有好多拼写的错误。除此之外创建节点出错。然后就是链表翻转的返回值出错。这道题主要涉及如何找到链表的中间节点,如何翻转链表,如何将两个链表拼接起来。
代码:
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null)
return;
ListNode slow = head;
ListNode fast = head;
// 找到中间结点
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode second = slow.next;
// 注意置空,分为两个链表
// 第一个链表的长度大于(+1)等于第二个链表长度
slow.next = null;
// 反转后半链表
second = reverseList(second);
ListNode first = head;
// 合并两个链表,画图模拟
// 把第二个链表插在第一个链表中
while (second != null) {
// 暂存第一个后续结点
ListNode next = first.next;
first.next = second;
second = second.next;
first = first.next;
first.next = next;
first = first.next;
}
}
// 就地翻转链表
private ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
执行最快的代码:
这两种代码的思路基本上是一样的,只不过写法上不同。
class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null || head.next.next == null)
return;
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
if(fast != null)
slow = slow.next;
fast = head;
while(fast.next != slow)
fast = fast.next;
fast.next = null;
ListNode prev = null;
while(slow != null){
ListNode next = slow.next;
slow.next = prev;
prev = slow;
slow = next;
}
while(head != null && prev != null){
ListNode next = head.next;
ListNode pnext = prev.next;
head.next = prev;
head.next.next = next;
head = next;
prev = pnext;
}
}
}