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; - 先移动temphead到index of m处,然后对index of m到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;
}
}
网友评论