简介
直接使用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;
}
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》