LeetCode 25. Reverse Nodes in k-Group
来源:互联网 发布:淘宝达人申请直播入口 编辑:程序博客网 时间:2024/05/29 11:59
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->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Subscribe to see which companies asked this question.
对一个链表,每k个节点进行一次逆序。
新建一个链表,每次逆转后,加入该链表:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(head==null||k==1){ return head; } int len = 0; ListNode p = head; while(p!=null){ len++; p = p.next; } int time = len/k; ListNode q = head; ListNode beg = head; ListNode tem = null; ListNode ans = new ListNode(0); p = ans; for(int i=0;i<len;i++){ if(time>0){ if((i+1)%k==0){ tem = q.next; q.next = null; p.next = reserve(beg); time--; while(p.next!=null){ p = p.next; } beg = tem; q = tem; } else{ q = q.next; } } else{ p.next = q; } } return ans.next; } public ListNode reserve(ListNode head){ ListNode p = head; ListNode pre = null; ListNode tem = p; while(p!=null){ tem = p.next; p.next = pre; pre = p; p = tem; } return pre; }}
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
- storm和kafka结合的一个小问题
- NYoj 26 孪生素数问题
- Linux:守护进程解析、如何实现守护进程
- Linux:守护进程详解及实现
- Shiro+SpringMVC
- LeetCode 25. Reverse Nodes in k-Group
- Python练习题目2
- 474. Ones and Zeroes
- 菜鸟速成记-IDL语法基础
- 2015年书单
- 2016年书单
- Android中的资源
- 在Android studio 里面通过Open Module Settings还是没办法彻底删除项目。
- C程序设计语言_vim小技巧