赞
踩
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[1,4,2,3]
示例 2:
输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]
提示:
链表的长度范围为 [1, 5 *
1
0
4
10^4
104]
1 <= node.val <= 1000
思路
乍看这题十分复杂,但仔细思考后发现原题可以拆解成找到链表中点、反转链表和拼接链表三个过程。首先,找到链表中点,将中点右边的部分进行翻转,之后将两个链表中的节点依次合并即可
代码
class Solution { public ListNode reverse(ListNode head) { ListNode pre = null; ListNode cur = head; ListNode next = null; while(cur!=null){ next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } public void reorderList(ListNode head) { if(head==null) return ; ListNode dummy = new ListNode(-1); dummy.next = head; ListNode fast = dummy; ListNode slow = dummy; while(fast!=null && fast.next!=null){ fast = fast.next.next; slow = slow.next; } ListNode head2 = reverse(slow.next); slow.next = null; ListNode cur = head; ListNode cur2 = head2; ListNode next = null; ListNode next2 = null; while(cur2!=null){ next2 = cur2.next; next = cur.next; cur.next = cur2; cur2.next = next; cur=next; cur2 = next2; } return; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。