【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
- LeetCode(25)Reverse Nodes in K-Group
- [leetcode 25]Reverse Nodes in k-Group
- [leetcode #25]Reverse Nodes in k-Group
- leetcode 25 Reverse Nodes in k-Group
- Leetcode 25 Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- LeetCode 25: Reverse Nodes in k-Group
- leetcode 25 -- Reverse Nodes in k-Group
- leetcode 25:Reverse Nodes in k-Group
- leetcode 25: Reverse Nodes in k-Group
- [Leetcode 25] Reverse Nodes in k-Group
- Leetcode#25||Reverse Nodes in k-Group
- LeetCode 25 Reverse Nodes in k-Group
- leetcode-25 Reverse Nodes in k-Group
- LeetCode 25: Reverse Nodes in k-Group
- Leetcode #25 Reverse Nodes in k-Group
- LeetCode 25:Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- 求出每年每月的日历
- UVa-1225
- C++学习笔记 Day 6
- VisualBox 下部署Ubuntu系统
- Android中使用开源框架EventBus3.0实现Fragment之间的通信交互
- 【LeetCode 25】 Reverse Nodes in K-Group
- 面试之内存泄露的原因
- 用cocos2dx 3.0开发球球大作战
- Codeforces768C Jon Snow and his Favourite Number
- 八:Java语言基础组成——运算符之位运算符和三元运算符
- 多个线程多个锁
- hihoCoder Challenge 27 #1469 : 福字 dp
- 数论常见定理汇总
- 常用地址(java)