【发布时间】:2018-12-06 07:10:46
【问题描述】:
给定一个单链表L:L0→L1→…→Ln-1→Ln, 重新排序为:L0→Ln→L1→Ln-1→L2→Ln-2→…
您不能修改列表节点中的值,只能更改节点本身。
我的解决方案是这样的。
我的想法是我们首先找到中间元素,然后将列表从中间的下一个元素反转到结束,然后合并它们,但我的问题是,如果主要功能类似于 public ListNode reorderList(ListNode头),那么我应该返回什么来获取整个列表。在此先感谢。
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
ListNode mid = findMiddle(head);
ListNode tail = reverse(mid.next);
mid.next = null;
merge(head, tail);
}
//to find the middle node of linked list
private ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
//to reverse the nodes in linked list
private ListNode reverse(ListNode head) {
ListNode prev = null;
ListNode curr = head;
ListNode next = null;
while(curr!=null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
//to merge both the start and tail node.
private void merge(ListNode headA, ListNode headB) {
ListNode dummy = new ListNode(0);
while (headA != null && headB != null) {
dummy.next = headA;
headA = headA.next;
dummy = dummy.next;
dummy.next = headB;
headB = headB.next;
dummy = dummy.next;
}
if (headA != null) {
dummy.next = headA;
} else if (headB != null) {
dummy.next = headB;
}
}
}
【问题讨论】:
标签: java pointers merge linked-list reorderlist