简介

直接使用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;
    }
}
posted on 2021-05-31 12:03  HDU李少帅  阅读(28)  评论(0编辑  收藏  举报