zoukankan      html  css  js  c++  java
  • #25 Reverse Nodes in k-Group

    题目链接:https://leetcode.com/problems/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 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


    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* reverseKGroup(struct ListNode* head, int k) {
    	if (k <= 1)
    		return head;
    	struct ListNode* dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
    	dummy->next = head;
    	struct ListNode* reversedRear = dummy;			//记录已逆转链表的尾节点
    	int len = 0;
    	while (reversedRear = reversedRear->next)		//暂时用来计算链表的长度
    		++len;
    	reversedRear = dummy;		//计算完长度后恢复记录一逆转链表的尾节点
    	if (k > len) {				//假设长度len不满一个处理段(k个),不须要逆转
    		free(dummy);
    		return head;
    	}
    	int pass = len / k;			//有pass段须要逆转,每趟逆转一段
    	struct ListNode *p, *q, *r;	//三个指针实现链表逆转。分别标记前一个、当前、后一个要处理指针的节点
    	while (pass--) {			//每趟逆转k个节点
    		p = head;
    		q = p->next;
    		for (int i = 1; i < k; ++i) {	//将当前处理段中间的指向逆转
    			r = q->next;
    			q->next = p;			//逆转指针
    			p = q;
    			q = r;
    		}
    		reversedRear->next = p;		//将当前处理段连接到已逆转链表尾部
    		head->next = q;	        	//将当前处理连接到未处理链表
    		reversedRear = head;		//更新已逆转链表的尾部
    		head = head->next;			//更新未处理表链头部
    	}
    	reversedRear->next = head;		//将剩余不满k个节点链表直接连接到已逆转链表尾部
    	head = dummy->next;
    	free(dummy);
    	return head;
    }


  • 相关阅读:
    checked、disabled在原生、jquery、vue下不同写法
    大白话理解闭包及相关笔试题
    reduce多种方法计算数组中某个值的出现次数
    js原生_获取url键值对
    弹窗和遮罩层的显示隐藏及空白区域关闭
    tab选项卡切换(js原生、jQuery )
    大白话理解this
    js---通过arguments来获取指定参数
    js-字符串方法
    登录linux,输入ls显示anaconda-ks.cfg cobbler.ks ....., 原因在于root@ ~ / 区别
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6762189.html
Copyright © 2011-2022 走看看