leetcode 92 翻转链表 II

简介

直接使用reverse, 进行值的替换, 链表翻转实在是太烦了

code

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        vector<int> v;
        ListNode *p = head;
        while(p){
            v.push_back(p->val);
            p=p->next;
        }
        reverse(v.begin() + (left - 1), v.begin() + (right));
        p = head;
        int index = 0;
        while(p){
            p->val = v[index];
            index ++;
            p = p->next;
        }
        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 reverseBetween(ListNode head, int m, int n) {
        List<Integer> v = new ArrayList<Integer>();
        ListNode p = head;
        while(p != null){
            v.add(p.val);
            p=p.next;
        }
        List<Integer> vv = new ArrayList<Integer>();
        for(int i=m-1; i<n; i++){
            vv.add(v.get(i));
        }
        Collections.reverse(vv);
        for(int i=m-1; i<n; i++){
            v.set(i, vv.get(i-m+1 ));
        }
        p = head;
        int index = 0;
        while(p != null){
            p.val = v.get(index);
            index++;
            p = p.next;
        }
        return head;
    }
}
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/14830820.html