题目要求:
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
题目大意:
给定一个链表及一个变量K,每K个节点进行一次翻转
解题思路:
将原链表按K个节点分别进行翻转,再拼接,具体做法:
- 判断该链表是否为空,或长度小于K——返回该链表
- 翻转前K个节点
- 将剩余的节点作为新链表,进行迭代
- 返回新链表
代码如下:
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;
}