leetcode 25. Reverse Nodes in k-Group

一 题目

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list's nodes, only nodes itself may be changed.

二 分析

给定一个链表,每次反转k个节点并返回反转后的链表。如果节点的个数不是k的倍数,节点后面剩下的部分就不用反转。

hard 级别。

  上一题是两两交换,这样 LeetCode 24. Swap Nodes in Pairs  这样next 与next.next还是很绕。

本题扩展到了K个节点。所以从题目是理解就是两部分,一部分找到这个K个节点,再进行反转。

分析思路:

通常链表类题目,为了记录当前最新的头结点的位置而引入的 resnode .新赋值cur节点从head开始,往后遍历,次数==k,就要进行反转,否则指向下一个节点cur = cur.next。这样看理清思路了,可是这题目我卡在反转了。

0->1->2->3->4->5
 |        |  |
pre      cur next

0->3->2->1->4->5
    |     |  |
   cur   pre next

看了网上大神的代码: https://www.cnblogs.com/grandyang/p/4441324.html

public static void main(String[] args) {
		ListNode node1 = new ListNode(1);
		node1.next = new ListNode(2);
		node1.next.next = new ListNode(3);
		node1.next.next.next = new ListNode(4);
		node1.next.next.next.next = new ListNode(5);
		ListNode res = reverseKGroup(node1 ,3);
		while(res != null){
			System.out.print(res.val+"->");
			res = res.next;
		}
	}
	
	//两步,1找到,2 反转
    public  static ListNode reverseKGroup(ListNode head, int k) {
    	if(head == null|| head.next == null|| k<=1){
    		return head;
    	}
    	ListNode res = new ListNode(0);
    	res.next = head;
    	ListNode pre = res;
    	ListNode cur = head;
    	
    	for(int i=1;cur != null;i++){
    		if(i%k==0){
    			pre = reverseStep(pre,cur.next);
    			cur = pre.next;
    		}else{
    			cur = cur.next;
    		}   		
    	}    	
		return res.next;        
    }
    
    private static ListNode reverseStep(ListNode pre,ListNode next){
    	ListNode last = pre.next;
    	ListNode cur = last.next;
    	while(cur != next){
    		last.next = cur.next;
    		cur.next = pre.next;
    		pre.next = cur;
    		cur = last.next;
    	}
		return last;    	
    }
    static class ListNode {
	     int val;
	      ListNode next;
	      ListNode(int x) { val = x; }
   }

Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Nodes in k-Group.

Memory Usage: 38.8 MB, less than 24.14% of Java online submissions forReverse Nodes in k-Group.

关键是反转代码不好理解。

 

todo...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值