LeetCode题解——Reverse Nodes in k-Group
来源:互联网 发布:淘宝商品曝光量在哪看 编辑:程序博客网 时间:2024/06/06 07:04
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
思路很简单,第一步判断这条链的长度是否是大于k的,如果不是,则直接返回。
若是,翻转前面的k个元素,在对剩余的链做reversKgroup的递归调用,最后将这些链拼接起来
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode* curr = head; int count = 0; while(count!=k && curr!=NULL)//find the K+1 Node { curr=curr->next; count++; } if(count!=k) return head; curr = reverseKGroup(curr,k); ListNode *next; while(count>0) { next = head->next; head->next = curr; curr = head; head = next; count--; } return curr; } ListNode* reversLinkedList(ListNode* head){ ListNode* previous = NULL; ListNode* next = NULL; while(head!=NULL){ next = head->next; head->next = previous; previous = head; head = next; } return previous; }};
0 0
- LeetCode题解——Reverse Nodes in k-Group
- LeetCode题解: Reverse Nodes in k-Group
- LeetCode 题解(36): Reverse Nodes in k-Group
- LeetCode题解-25-Reverse Nodes in k-Group
- leetcode题解c++ | 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——Reverse Nodes in k-Group
- leetcode——Reverse Nodes in k-Group
- leetcode 025 —— Reverse Nodes in k-Group
- LeetCode 之 Reverse Nodes in k-Group — C 实现
- LeetCode:Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group
- LeetCode : Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- [Leetcode] reverse nodes in K-Group
- [LeetCode]Reverse Nodes in k-Group
- maven 学习笔记 之一.本地安装配置
- Powershell脚本设置SharePoint自动更新托管账户密码
- 谈谈Markdown的认识与入门
- INSTALL_FAILED_UID_CHANGED解决办法
- jquery常用选择器
- LeetCode题解——Reverse Nodes in k-Group
- 会话描述协议(SDP)介绍
- &
- hdoj 1166 敌兵布阵(线段树||树状数组)
- 两个简单的word转pdf的方法
- C++设计模式:单例模式
- csu 1507: 超大型LED显示屏(要重新敲一遍)
- IOC容器——Ninject
- 世界上最难的游戏?你相信吗?