// 冲刺046
class Solution {
public void reorderList(ListNode head) {
int num = 0;
ListNode first = head;
ListNode second = head;
while (second != null) {
second = second.next;
num++;
}
second = head;
for (int i = 0; i < (num + 1) / 2; i++) {
second = second.next;
}
second = reverse(second);
for (int i = 0; i < num / 2; i++) {
ListNode next = first.next;
ListNode tempNext = second.next;
first.next = second;
second.next = next;
first = next;
second = tempNext;
}
first.next = null;
}
ListNode reverse(ListNode head) {
ListNode before = null;
ListNode next = null;
ListNode now = head;
while(now != null) {
next = now.next;
now.next = before;
before = now;
now = next;
}
return before;
}
}
Leetcode_143_重排链表_链表
最新推荐文章于 2024-04-11 13:10:02 发布
本文介绍了一种使用双指针技巧的方法,详细讲解如何在Java中实现链表的重新排序和部分逆序操作。首先通过遍历获取链表长度,然后调整指针位置进行一次逆序和后续的插入操作,最后返回调整后的链表头节点。

1199

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



