题解 | #重排链表#
重排链表
https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public void reorderList(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode slow = dummy; ListNode fast = dummy; while(fast!=null && fast.next!=null){//此时还没有到达中点位置 slow = slow.next; fast = fast.next; if(fast.next!=null){ fast = fast.next; } } ListNode tmp = slow.next;//中点后的链表 slow.next = null; link(head,reverseList(tmp),dummy); } //将两个链表连接起来 public void link(ListNode node1,ListNode node2,ListNode head){ ListNode cur = head; while(node2!=null){ //构建链表 ListNode tmp = node1.next; cur.next = node1; node1.next = node2; cur = node2; node1 = tmp; node2 = node2.next; } if(node1!=null){ cur.next = node1; } } //反转链表 public ListNode reverseList(ListNode node){ ListNode pre = null; ListNode cur = node; while(cur!=null){ ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }