链表以k个一组进行翻转(2014美团研发笔试)
来源:互联网 发布:网络挣钱项目 编辑:程序博客网 时间:2024/06/09 16:47
给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,则翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6。
ListNode *reverseKGroup(ListNode *head, int k){ if (head == nullptr || head->next == nullptr || k < 2) return head; ListNode *next_group = head; for (int i = 0; i < k; ++i) { if (next_group) next_group = next_group->next; else return head; }// next_group is the head of next group// new_next_group is the new head of next group after reversion ListNode *new_next_group = reverseKGroup(next_group, k); ListNode *prev = NULL, *cur = head; while (cur != next_group) { ListNode *next = cur->next; cur->next = prev ? prev : new_next_group; prev = cur; cur = next; } return prev; // prev will be the new head of this group}
若末尾不足K的也进行翻转,则如下
/* Reverses the linked list in groups of size k and returns the pointer to the new head node. */struct node *reverse (struct node *head, int k){ struct node* current = head; struct node* next; struct node* prev = NULL; int count = 0; /*reverse first k nodes of the linked list */ while (current != NULL && count < k) { next = current->next; current->next = prev; prev = current; current = next; count++; } /* next is now a pointer to (k+1)th node Recursively call for the list starting from current. And make rest of the list as next of first node */ if(next != NULL) { head->next = reverse(next, k); } /* prev is new head of the input list */ return prev;}
见Geeks、Leetcode
- 链表以k个一组进行翻转(2014美团研发笔试)
- 链表翻转(按K个一组)
- 每K个元素翻转一次链表,若最后剩余元素不足K个,不进行翻转(美团2014校招试题)
- 美团笔试题:k链表翻转
- LeetCode | Reverse Nodes in k-Group(k个结点一组翻转链表)
- 链表翻转,每k个进行翻转
- 以k个元素为一组反转单向链表
- 以k个元素为一组反转单向链表
- [LeetCode] Reverse Nodes in k-Group每k个一组翻转链表
- Leetcode017--链表k个结点一组翻转
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- [2014美团网笔试]给定一个单链表和一个整数k,要求每隔k个元素翻转链表
- Young矩阵查找(2014美团研发笔试)
- 美团2015 研发笔试 (1)
- 美团2015 研发笔试 (2)
- 链表翻转(每K个结点进行一次逆置)
- 链表以k单位翻转
- [LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序
- mysql 使用service mysqld start 提示未识别服务 进入/etc/rc.d/init.d 下面未发现有mysqld解决方法
- 110705 Summation of Four Primes
- IOS工程中Info.plist文件详解
- 浅谈软件项目及流程管理
- Oracle联机备份和Data Pump基础
- 链表以k个一组进行翻转(2014美团研发笔试)
- Cocos2d-x快速打包脚本
- 206-矩形的个数
- Windows 常见数据类型及变量_常量命名规律
- Oracle中使用rank()over()排名的问题
- 日本42岁的女主播竟然转行做女优!!
- Maven
- rpm打包
- phonegap为何会出现中文乱码问题 解决方法