leetcode 25 K 个一组翻转链表

简介

简单题

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

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14768290.html