leetcode:Reverse Nodes in k-Group
来源:互联网 发布:任子行 知乎 编辑:程序博客网 时间:2024/06/06 13:02
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. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(head != null && k > 1){ int len = getLen(head); int remain = len % k; int groups = len / k; ListNode next = null; ListNode pre = head; ListNode tail = head; ListNode preTail = null; for(int i = 0; i < groups; ++i){ tail = pre; for(int j = 0; j < k; ++j){ ListNode temp =pre.next; pre.next = next; next= pre; pre = temp; } if(tail == head){ head = next; } if(preTail != null){ preTail.next = next; } preTail = tail; } if(preTail != null){ preTail.next = pre; } } return head; } public int getLen(ListNode list){ int len = 0; while(list != null){ ++len; list = list.next; } return len; }}
0 0
- 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
- LeetCode-Reverse Nodes in k-Group
- LeetCode - Reverse Nodes in k-Group
- LeetCode | Reverse Nodes in k-Group
- 【leetcode】Reverse Nodes in k-Group
- Leetcode: Reverse Nodes in k-Group
- leetcode Reverse Nodes in k-Group
- [LeetCode] Reverse Nodes in k-Group
- LeetCode题解: Reverse Nodes in k-Group
- 【Leetcode】Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- [Leetcode] Reverse Nodes in k-Group (Java)
- LeetCode(25)Reverse Nodes in K-Group
- CentOS安装MySql数据库
- [MFC] Clistctrl
- 输入优化
- Tomcat的压缩包安装和启动
- UIWebview打开doc,pdf 等文件
- leetcode:Reverse Nodes in k-Group
- Atlassian工具集和JIRA插件在敏捷项目管理中的应用实践
- java Map set list 理解
- VMware+Windgb+Win7内核驱动调试
- 如何使用iTunes恢复您的iPhone或iPad
- HDOJ 1113
- hdu 2200
- VC项目配置基础[phunxm]
- XML命名空间