Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (isValidSection(head, k) == false)
return head;
ListNode cur = head;
ListNode prev = null, next = null;
ListNode temp = cur;
int count = k;
//用next一个一个的去读取原链表,用prev去读取数据重新生成一个链表
while (count > 0) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
count--;
}
temp.next = reverseKGroup(cur, k);//递归
return prev;
}
//由于题目是重复进行某个动作,肯定要用递归,输入数据的判断跟后面递归做的判断相似,就写成一个方法
//k比ListNode的个数小,则返回false,否则true
public static boolean isValidSection(ListNode node, int k) {
ListNode cur = node;
while (cur != null && k > 0) {
cur = cur.next;
k--;
}
if (k > 0)
return false;
return true;
}
}
链表K个一组翻转
本文介绍了一种算法,该算法将链表中的节点每K个一组进行反转,并返回修改后的链表。如果节点数量不是K的倍数,剩余节点保持原样。此过程不改变节点值,仅调整节点顺序,并且只使用常量内存。
4890

被折叠的 条评论
为什么被折叠?



