赞
踩
给定一个单链表 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.
import java.util.Deque; import java.util.LinkedList; class Solution { public void reorderList(ListNode head) { if(head == null || head.next == null){ return ; } Deque<ListNode> dequeue = new LinkedList<>(); ListNode cur = head; while(cur != null){ dequeue.offer(cur); cur = cur.next; } while(!dequeue.isEmpty()){ head.next = dequeue.pollFirst(); head = head.next; if(!dequeue.isEmpty()){ head.next = dequeue.pollLast(); head = head.next; } } head.next = null; } }
import java.util.Deque; import java.util.LinkedList; class Solution { public void reorderList(ListNode head) { if(head == null || head.next == null){ return ; } //找到整个链表的中心点 ListNode fast = head; ListNode low = head; while(fast != null && fast.next != null){ fast = fast.next.next; low = low.next; } //反转后半段链表 ListNode pre = null; ListNode cur = low; ListNode temp = cur.next; cur.next = pre; cur = temp; while(cur != null){ temp = cur.next; cur.next = pre; pre = cur; cur = temp; } //前后两段链表混合 while(pre != null){ ListNode temp1 = head.next; ListNode temp2 = pre.next; head.next = pre; pre.next = temp1; head = temp1; pre = temp2; } } }
import java.util.Deque; import java.util.LinkedList; class Solution { public void reorderList(ListNode head) { if(head == null || head.next == null){ return ; } ListNode fast = head; ListNode low = head; while(fast != null && fast.next != null){ fast = fast.next.next; low = low.next; } if(fast != null){ low = low.next; } //反转链表。这里错了,造成pre最后一个结点无限循环。 但我不明白,为什么有错? ListNode pre = null; ListNode cur = low; while(cur != null){ ListNode temp = cur.next; cur.next = pre; pre = cur; cur = temp; } while(pre != null){ ListNode temp1 = head.next; ListNode temp2 = pre.next; head.next = pre; pre.next = temp1; head = temp1; pre = temp2; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。