zoukankan      html  css  js  c++  java
  • 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.

    If the number of nodes is not a multiple of k then left-out nodes in the end should remain asit is.

    You may not alter the values in the nodes, onlynodes 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

     

           思路:本题要求空间复杂度为O(1),因此不能用栈来翻转k个元素。所以,本题真正的难点在于,如何用有限的指针,实现链表中k个元素的翻转。代码如下:

    struct ListNode *reverseknode(struct ListNode *begin, int k)
    {
    	struct ListNode *endnext = begin;
    	while(k && endnext)
    	{
    		k--;
    		endnext = endnext->next;
    	}
    	if(k > 0)	return begin;
    
    	struct ListNode *reshead = endnext;
    	struct ListNode *p, *q;
    	p = begin;
    
    	while(p != endnext)
    	{
    		q = p->next;
    		p->next = reshead;
    		reshead = p;
    		p = q;
    	}
    
    	return reshead;
    	
    }
    struct ListNode* reverseKGroup(struct ListNode* head, int k) 
    {
    	struct ListNode *reshead, *p, *q, *r;
    
    	reshead = NULL;
    	p = head;
    
    	while(p != NULL)
    	{
    		q = reverseknode(p, k);
    
    		if(reshead == NULL)	reshead = q;
    		else r->next = q;
    
    		if(p == q)	break;
    
    		r = q;
    		while(r != p)
    		{
    			r = r->next;
    		}
    		p = p->next;
    	}
    	return reshead;
    }
    

      


  • 相关阅读:
    使用virtualenvwrapper隔离python环境
    Ubuntu创建launcher
    Python单步调试
    Jupyter增加内核
    扩展User增加部门字段
    EasyUI ComboBox默认值
    C#调用dll时的类型转换
    更改VisualStudio默认创建类和接口不加public问题
    IL学习资料
    服务注册中心,Eureka比Zookeeper好在哪里?
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/7247150.html
Copyright © 2011-2022 走看看