題目鏈接:25. Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k
at a time and return its modified list.
k
is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k
then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list’s nodes, only nodes itself may be changed.
題解
力扣將此題設置爲困難。不過我覺得這道題目並不難。
首先判斷是否爲空。
不爲空的話,用數組保存不超過 k
個數,如果有 k
個數,就逆序賦值到這 k
個結點,不足 k
個數直接退出。
返回原頭結點 head
即可。
時間複雜度:。
空間複雜度:一個一維數組,。
Java代碼
/**
* 2020-1-31 18:37:14
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) {
return null;
}
int[] arr = new int[k];// 保存k個數
ListNode hk = head;// 每k個結點的頭結點
while (hk != null) {// 每一段的頭結點是否存在
ListNode p = hk;// 移動指針
int len = 0;// 當前這一段有幾個結點
while (len < k && p != null) {// 找不超過k個結點直到爲空
arr[len] = p.val;// 保存結點的值
++len;// 個數加1
p = p.next;// 向後移動指針
}
if (len < k) {
break;// 不足k個結點,不用逆序,直接退出
}
for (int i = len - 1; i >= 0; --i) {// 有k個結點,逆序賦值
hk.val = arr[i];
hk = hk.next;
}
}
return head;
}
}
原文鏈接:https://blog.csdn.net/pfdvnah/article/details/104126675