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


  • 相关阅读:
    Dom之标签增删操作
    Dom实例:数据自增、搜索框及跑马灯
    Dom选择器及操作文本内容
    Tkinter单选框及滚动条
    Tkinter颜色方案举例
    TKinter之窗口美化 窗口大小、图标等
    TKinter之文本域与多窗口
    TKinter之菜单
    JavaScript 基本语法
    TKinter的常用组件
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6762189.html
Copyright © 2011-2022 走看看