首页 > 其他 > 详细

leetcode 25 K 个一组翻转链表

时间:2021-05-14 15:48:45      阅读:25      评论:0      收藏:0      [点我收藏+]

简介

简单题

code

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        vector<ListNode*> l;
        ListNode * p = head; 
        while(p){
            l.push_back(p);
            p = p->next;
            if(l.size() == k) {
                vector<int> v;
                for(auto it : l) {
                    v.push_back(it->val);
                }
                reverse(v.begin(), v.end());
                int index = 0;
                for(auto it : l) {
                    it->val = v[index];
                    index++;
                }
                l.clear();
            }
        }
        return head;
    }
};
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode[] l = new ListNode[k];
        int l_index = 0;
        ListNode p = head;
        while(p != null) {
            l[l_index] = p;
            l_index+=1;
            p = p.next;
            if(l_index == k) {
                ArrayList arraylist = new ArrayList();
                int v_index = 0;
                for(ListNode it : l){
                    arraylist.add(it.val);
                }
                Collections.reverse(arraylist);
                int index = 0;
                for(ListNode it : l) {
                    it.val = Integer.parseInt(String.valueOf(arraylist.get(index)));
                    index+=1;
                }
                l_index = 0;
            }
        }
        return head;
    }
}

java 中 ArrayList 有点类似 C++ 中的vector.
java中保存的可以说都是指针, 所以更改数据还是挺方便的.

leetcode 25 K 个一组翻转链表

原文:https://www.cnblogs.com/eat-too-much/p/14768290.html

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