反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL
5ms
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==n){
return head;
}
m = m-1;
n = n-1;
List<ListNode> list = new ArrayList();
ListNode cur = head;
while(cur!=null){
ListNode tmp = cur.next;
cur.next = null;
list.add(cur);
cur = tmp;
}
ListNode a;
ListNode b;
while(m<n){
a = list.get(m);
b = list.get(n);
list.set(m,b);
list.set(n,a);
m++;
n--;
}
ListNode newHead = list.get(0);
ListNode next;
for(int i=0;i<list.size()-1;i++){
next = list.get(i);
next.next = list.get(i+1);
}
return newHead;
}
}
优化4ms
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n){
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode cur = newHead;
for(int i=0;i<m-1;i++){
cur = cur.next;
}
ListNode first = cur;
ListNode last = cur.next;
ListNode pre = null;
cur = cur.next;
ListNode tmp;
for(int i=0;i<n-m+1;i++){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
first.next = pre;
last.next = cur;
return newHead.next;
}
}
优化3ms
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
for (int i = 0; i < m - 1; i++) {
prev = prev.next;
}
ListNode start = prev.next;
ListNode then = start.next;
for (int i = 0; i < n - m; i++) {
start.next = then.next;
then.next = prev.next;
prev.next = then;
then = start.next;
}
return dummy.next;
}
}
给定一个值3,需要对数组[1,2,3,4,5] 反转, 需要得到结果 [3,2,1,5,4]
public ListNode reversetTwo(ListNode head,int m,int total){
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode start = pre.next;
ListNode then = start.next;
for(int i=0;i<m-1;i++){
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
int n = total-m;
pre = start;
start = start.next;
then = then.next;
for(int i=0;i<n-1;i++){
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}