简介

直接使用reverse反转数组方法

code

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode * p = head;
        vector<int> v;
        while(p) {
            v.push_back(p->val);
            p = p->next;
        }
        reverse(v.begin(), v.end());
        p = head;
        int index = 0;
        while(p){
            p->val = v[index];
            p = p->next;
            index ++;
        }
        return head;
    }
};

java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode p = head;
        ArrayList<Integer> l = new ArrayList<Integer>(); // 使用arrayList Integer
        while(p != null){
            l.add(p.val);
            p = p.next;
        }
        Collections.reverse(l); // 对应sort
        p = head;
        int index = 0;
        while(p != null){
            p.val = l.get(index); // arraylist 智能这么获取数据
            p = p.next;
            index++;
        }
        return head;
    }
}

posted on 2021-05-16 19:49  HDU李少帅  阅读(25)  评论(0编辑  收藏  举报