題目要求:
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.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For 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
題目大意:
給定一個(gè)鏈表及一個(gè)變量K,每K個(gè)節(jié)點(diǎn)進(jìn)行一次翻轉(zhuǎn)
解題思路:
將原鏈表按K個(gè)節(jié)點(diǎn)分別進(jìn)行翻轉(zhuǎn),再拼接,具體做法:
- 判斷該鏈表是否為空,或長(zhǎng)度小于K——返回該鏈表
- 翻轉(zhuǎn)前K個(gè)節(jié)點(diǎn)
- 將剩余的節(jié)點(diǎn)作為新鏈表,進(jìn)行迭代
- 返回新鏈表
代碼如下:
public ListNode reverseKGroup(ListNode head, int k) {
if(k<=1 || head == null) return head;
int i = 0;
ListNode node = new ListNode(0);
node.next = head;
while(node.next != null) {
i++;
node = node.next;
}
if(i < k) return head;
ListNode var = head;
i = k;
while(i-- >1){
ListNode temp = var.next;
var.next = temp.next;
temp.next = head;
head = temp;
}
var.next = reverseKGroup(var.next,k);
return head;
}