zoukankan      html  css  js  c++  java
  • LeetCode:25 K个一组翻转链表

      想了想,毕竟以后可能还是敲Java得多,不如做题也改成Java好了。结果一做题,C++的惯性思维还是改不掉。在指针和对象引用互相转换,真是吐了。题目倒是不难,ac了之后看了看题解,再稍微改了改。

      不得不说,以后还是用Java写好了。免得把这些有的没的带到工作中。

      既然是翻转,就还是用头插法好了。其他的部分也没什么难度,子链表取下来,翻转完了,再重新连上。子链表前一个节点和后一个节点的引用需要保存一下,以便连上。

    class Solution {
    
        private ListNode[] reverse(ListNode begin,ListNode end){
            ListNode a = begin;
            ListNode b = null;
            ListNode t = new ListNode(0);
            t.next = null;
            while(a!=null){
                b = a.next;
                a.next = null;
                a.next = t.next;
                t.next = a;
                a = b;
                
            }
            
            return new ListNode[]{end,begin};
        }
    
        public ListNode reverseKGroup(ListNode head, int k) {
           
           
            ListNode n = new ListNode(-1);
            n.next = head;
         //   ListNode next = null;
            ListNode pre = n;
           
           
            ListNode begin = head;
            ListNode end = head;
            while(end!=null){
                for(int i=1;i<k;i++){
                    end = end.next;
                    if(end==null){
                        return n.next;
                    }
                }
                ListNode nex = end.next;
                end.next = null;
    
                ListNode[] r = reverse(begin,end);
                r[1].next = nex;
                pre.next = r[0];
                pre = r[1];
                begin = end = r[1].next;
                
            }
            
            return n.next;
        }
        
    }
  • 相关阅读:
    统计字符
    两军交锋
    FatMouse' Trade
    A + B Problem II
    Number Sequence
    Max Sum
    类的设计
    类与对象
    面向对象思想
    第一个OC程序
  • 原文地址:https://www.cnblogs.com/dloooooo/p/13755678.html
Copyright © 2011-2022 走看看