首页 > 其他 > 详细

25. k个一组翻转链表-LeetCode

时间:2019-05-19 14:23:43      阅读:79      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

心得:反转链表加强版,加头节点简化操作,然后写一个方法调用

反转链表,注意next的操作,边界条件!!

 

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10      public ListNode reverseKGroup(ListNode head, int k) {
11           if(head==null)
12               return null;
13             ListNode rhead=new ListNode(-1);
14             rhead.next=head;
15             ListNode tmp=run(rhead,k);
16             while(tmp!=null)
17             {
18                 tmp=run(tmp,k);
19             }
20             return rhead.next;
21         }
22       public ListNode run(ListNode head,int k)
23       {
24           ListNode start=head.next;
25           ListNode next=null;
26           ListNode end=null;
27           ListNode ans=null;
28           int sum=k;
29           while(start!=null&&sum>0)
30           {
31               start=start.next;
32              sum--;
33           }
34           if(sum!=0)
35               return null;
36           start=head.next;
37         //  next=null;
38           if(start.next!=null)
39               next=start.next;
40           if(start.next!=null&&start.next.next!=null)
41               end=start.next.next;
42         while(next!=null&&k>1)    
43         {
44             next.next=start;
45             start=next;
46             next=end;
47             if(end!=null)
48              end=end.next;
49             k--;
50         }
51         ans=head.next;
52           head.next.next=next;
53           head.next=start;
54           return ans;              
55       }
56 }

 

25. k个一组翻转链表-LeetCode

原文:https://www.cnblogs.com/pc-m/p/10888941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!