https://leetcode.com/problems/reverse-linked-list/description/
https://leetcode.com/problems/reverse-linked-list-ii/description/
解題思路:
- next = tempHead.next;
tempHead.next = tempHead.next.next;
next.next = head;
head = next; - 先移動(dòng)temphead到index of m處,然后對(duì)index of m到n處進(jìn)行逆轉(zhuǎn),最后把m之前的node連接到temphead
代碼:
class Solution {
public ListNode reverseList(ListNode head) {
if(head != null && head != null){
ListNode tempHead = head;
ListNode next = null;
while(tempHead != null && tempHead.next != null){
next = tempHead.next;
tempHead.next = tempHead.next.next;
next.next = head;
head = next;
}
}
return head;
}
}
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode tempHead = head, preHead = head, next = null;
int m1 = m, n1 = n;
while(--m1 > 0){
tempHead = tempHead.next;
}
ListNode pilot = tempHead;
while(n1-- - m > 0){
next = pilot.next;
pilot.next = pilot.next.next;
next.next = tempHead;
tempHead = next;
}
while(--m > 1) {
preHead = preHead.next;
}
preHead.next = tempHead;
return head;
}
}