小程式消除點選時高亮,點選背景是有背景色
阿新 • • 發佈:2020-12-19
求助這個反轉為什麼m=3,n=4時,輸出會少一位
/**
* 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){
return null;
}
//定義兩個指標用來迭代
ListNode cur = head;
ListNode pre = null;
//移動迭代指標到m處
while(m>1){
pre = cur;
cur = head.next;
m--;
n--;//n--在這裡表示後續迭代的次數
}
/*保留此時的pre,cur指標處,為中間待反轉結點的頭部,與頭部前一個結點,
*後續反轉後該頭部即為尾部,連線原先連結串列的後部,pre(頭部前一個結點)連線反轉後的頭*/
ListNode con = pre;
ListNode tail = cur;
//迭代反轉
ListNode tem = null;
while(n>0){
tem = cur.next;
cur.next = pre;
pre = cur;
cur = tem;
n--;
}
//判空
//連線頭部
if (con != null){
con.next = pre;
//con=null,說明M=1,無需連線頭部
}else{
head = pre;
}
//連線尾部
tail.next = cur;
return head;
}
}