题目:
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
与上一题几乎一模一样,采用递归方法,唯一需要区别的是前面两个节点的交换,变成了长度为k的链表的逆序。
关于逆序算法,只需要设置一个pre的节点,用来存储当前节点的前一个节点即可。
public class No24_ReverseNodesInKGroup {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static void main(String[] args){
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
ListNode n5 = new ListNode(5);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
ListNode head = n1;
ListNode x = reverseKGroup(head, 3);
while(x!=null){
System.out.println(x.val);
x = x.next;
}
}
public static ListNode reverseKGroup(ListNode head, int k) {
int l = 0;
ListNode node = head;
while(node!=null && l<k){
node = node.next;
l++;
}
if(l<k) return head;
//node为递归的输入参数,需要对head的长度k链表逆序
ListNode pre = reverseKGroup(node, k);
while(l>0){
ListNode tmp = head.next;
head.next = pre;
pre = head;
head = tmp;
l--;
}
return pre;
}
}
本文介绍了一种算法,该算法将链表中的节点每K个一组进行反转,并返回修改后的链表。如果节点数量不是K的倍数,则末尾剩余的节点保持不变。通过递归方法实现链表的局部反转,同时确保只使用常量内存。
:Reverse Nodes in k-Group&spm=1001.2101.3001.5002&articleId=37934679&d=1&t=3&u=d2ffb386a7e349c2b4429c45828ff644)
1504

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



