LeetCode OJ算法题(二十四):Reverse Nodes in k-Group

本文介绍了一种算法,该算法将链表中的节点每K个一组进行反转,并返回修改后的链表。如果节点数量不是K的倍数,则末尾剩余的节点保持不变。通过递归方法实现链表的局部反转,同时确保只使用常量内存。

题目:

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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值