【LeetCode 25】 Reverse Nodes in K-Group

来源:互联网 发布:植物精灵 mac 编辑:程序博客网 时间:2024/06/05 02:25
/****************************LeetCode 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.k is a positive integer and is less than or equal to the length of the linked 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->5For k = 2, you should return: 2->1->4->3->5For k = 3, you should return:****************************//********************思想:1.遍历单链表,统计节点个数count2.count<k 则返回,否则 翻转次数为 count/k3.循环count/k次,翻转4.每次翻转要记录两个量 翻转链表的 头节点 和 尾节点5.判定翻转count/k次后,将后续未翻转节点连接到翻转后的链表后**************************/ListNode *ReverseNodesInKGroup(ListNode *head, int k){if (k <= 1 || head == NULL || head->next == NULL){return head;}//判定节点个数int count = 0;ListNode *preHead = head;while (preHead != NULL){count++;preHead = preHead->next;}if (count<k){return head;}//进行count/k次翻转ListNode *tempHead = head;ListNode *firstTail = NULL;//前段翻转后的尾节点ListNode newHead(1);firstTail = &newHead;int num = count / k;  //翻转的次数for (int ii = 0; ii < num; ii++){ListNode *secondTail = tempHead;//尾节点//进行翻转count = k - 1;ListNode *pre = tempHead;ListNode *curr = pre->next;ListNode *rear = curr->next; while (count-- >0 && rear != NULL){curr->next = pre;pre = curr;curr = rear;rear = rear->next;}if (count != -1 && rear == NULL){curr->next = pre;pre = curr;curr = rear;}secondTail->next = curr;firstTail->next = pre;firstTail = secondTail;tempHead = curr;}return newHead.next;}
0 0