206. Reverse Linked List I and I

2018-07-31  本文已影响0人  becauseyou_90cd

https://leetcode.com/problems/reverse-linked-list/description/
https://leetcode.com/problems/reverse-linked-list-ii/description/
解题思路:

  1. next = tempHead.next;
    tempHead.next = tempHead.next.next;
    next.next = head;
    head = next;
  2. 先移动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;
}

}

上一篇 下一篇

猜你喜欢

热点阅读