Leetcode143. 重排链表
题目:
给定一个单链表 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.
题解:
1.定义快慢指针,慢指针走一步,快指针走两步,当快指针到达null时,慢指针走一半,此时的慢指针刚好是链表的中间点;
2.拿到慢指针的节点,将慢指针给另一个指针pre,再将前后两部分链表断开,翻转后半部分链表;
3.将前后两部分链表链接起来即可。
1 -> 2 -> 3 -> 4 -> 5 -> 6
第一步,将链表平均分成两半
1 -> 2 -> 3
4 -> 5 -> 6
第二步,将第二个链表逆序
1 -> 2 -> 3
6 -> 5 -> 4
第三步,依次连接两个链表
1 -> 6 -> 2 -> 5 -> 3 -> 4
java代码:
/**
* @param head
*/
public static void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode pre = slow.next;
//断开前后两个链表
slow.next = null;
pre = reverse(pre);
//链表节点依次连接
while (pre!=null){
ListNode tmp = pre.next;
pre.next=head.next;
head.next=pre;
head=pre.next;
pre =tmp;
}
}
/**
* 翻转链表
*
* @param head
* @return
*/
public static ListNode reverse(ListNode head) {
if (head == null) return null;
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
LeetCode143重排链表算法解析
本文详细解析了LeetCode143题——重排链表的算法实现,通过定义快慢指针找到链表中点,翻转后半部分链表,并将前后两部分链表交替连接,最终实现链表的重排。
410

被折叠的 条评论
为什么被折叠?



