题目地址
LeetCode#725 Split Linked List in Parts
题目描述
Given a (singly) linked list with head node root
, write a function to split the linked list into k
consecutive linked list “parts”.
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.
Return a List of ListNode’s representing the linked list parts that are formed.
Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]
Example 1:
1 | Input: |
Example 2:
1 | Input: |
Note:
- The length of
root
will be in the range[0, 1000]
. - Each value of a node in the input will be an integer in the range
[0, 999]
. k
will be an integer in the range[1, 50]
.
解题思路
题目要求将链表分割 K 条,并满足当链表长度 Len % K == N 的时候,则前 N 条子链的长度为 Len / K + 1,其他的长度为 Len / K。当某一个子链长度为0时,数组里存 NULL 。
解题代码
1 | /** |