首页 > 其他 > 详细

leetcode 92 翻转链表 II

时间:2021-05-31 15:56:02      阅读:12      评论:0      收藏:0      [点我收藏+]

简介

直接使用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;
    }
}

leetcode 92 翻转链表 II

原文:https://www.cnblogs.com/eat-too-much/p/14830820.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!