标签:leetcode c linked list
题目链接: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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode c linked list
原文地址:http://blog.csdn.net/ice_camel/article/details/46956029