美文网首页
206. Reverse Linked List I and I

206. Reverse Linked List I and I

作者: becauseyou_90cd | 来源:发表于2018-07-31 01:29 被阅读0次

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;
}

}

相关文章

网友评论

      本文标题:206. Reverse Linked List I and I

      本文链接:https://www.haomeiwen.com/subject/hstcvftx.html