题解 | #重排链表#
重排链表
https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b
import java.util.*; /** * 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) { if (head == null) { return; } ListNode pNode = new ListNode(0); pNode.next = head; List<ListNode> list = new ArrayList<>(); while (pNode.next != null) { pNode = pNode.next; list.add(pNode); } List<ListNode> list1 = new ArrayList<>(list.size()); for (int i = 0; i < list.size(); i ++) { if (i == 0) { list1.add(list.get(i)); continue; } if (i % 2 == 0) { list1.add(list.get(i / 2)); } else { list1.add(list.get(list.size() - 1 - i / 2)); } } for (int i = 0; i < list1.size() - 1; i ++) { list1.get(i).next = list1.get(i + 1); } list1.get(list.size() - 1).next = null; } }