leetcode:Reverse Nodes in k-Group
来源:互联网 发布:海信网络电视怎么样 编辑:程序博客网 时间:2024/06/14 14:22
递归,每次取k个元素。然后对这k个元素处理,返回{k个元素}+reverseKGroup(tail,k)
比如1-2-3-4-5-6,k=4,那就先处理1-2-3-4,tail=5,5-6后续再处理。
处理过程是1(head,p1)-2(p2)-3-4,p1是当前最左边的元素,head是原来的头,p2是原来头下面的元素。
然后把p2移到p1左边:2(p1)-1(head)-3(p2)-4
然后再把p2移到p2左边:3(p1)-2-1(head)-4(p2)
一共移k-1次,最后得到4(p1)-3-2-1(head),p2=tail;
然后head=p1即可。
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {int i;
if(head==null || k==1)
return head;
ListNode pre=new ListNode(0);
pre.next=head;
for(i=0;i<k;i++)
{
if(pre.next!=null)
pre=pre.next;
else
return head;
}
ListNode tail=pre.next;
ListNode p1=head;
ListNode p2=head.next;
i=1;
while(i<k)
{
head.next=p2.next;
p2.next=p1;
p1=p2;
p2=head.next;
i++;
}
head.next=reverseKGroup(tail,k);
head=p1;
return head;
}
}
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
- storm中,ack与fail信息的处理
- javaweb之Session完成用户登录
- 结合MongoDB开发LBS应用
- 设计模式Before-after之抽象工厂模式
- struts1与struts2比较
- leetcode:Reverse Nodes in k-Group
- mysql通过表和function模拟oracle的sequence
- MINA框架学习
- linux安装mongoDB
- 说一句你熟悉的歌词,你是我的眼
- Oracle字符集的查看查询和Oracle字符集的设置修改
- Windows Phone笔记(手机应用开发笔记)
- volatile在多线程中的使用
- 程序:Bwriter.java