206. Reverse Linked List I and II

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

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容