简介

简单题

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中保存的可以说都是指针, 所以更改数据还是挺方便的.

posted on 2021-05-14 13:54  HDU李少帅  阅读(33)  评论(0编辑  收藏  举报