现在的位置: 主页 > 新闻中心 > 文章列表

#25 Reverse Nodes in k-Group

作者:程力专用汽车股份有限公司 来源:www.chLiw.com 发布时间:2017-09-05 12:24:52
#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.

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

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:武汉网站建设公司 https://www.jingchucn.com/zt/wuhan_wangzhanjianshe/

上一篇:python的tkinter可以更换红色的图标“Tk” 下一篇:最后一页