[Leetcode] Reverse Linked List 反转链表

Reverse Linked List I

Reverse a singly linked list.

click to show more hints.

Hint: A linked list can be reversed either iteratively or recursively. Could you implement both?

递归法

复杂度

时间 O(N) 空间 O(N) 递归栈空间

思路

基本递归

代码

public class Solution {
    
    ListNode newHead;
    
    public ListNode reverseList(ListNode head) {
        reverse(head);
        return newHead;
    }
    
    private ListNode reverse(ListNode n){
        if( n == null || n.next == null){
            newHead = n;
        } else {
            ListNode prev = reverseList(n.next);
            prev.next = n;
        }
        return n;
    }
}

迭代法

复杂度

时间 O(N) 空间 O(1)

思路

基本迭代

代码

java

public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode p1 = head;
        ListNode p2 = p1.next;
        while(p2 != null){
            ListNode tmp = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = tmp;
        }
        head.next = null;
        return p1;
    }
}

python

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p1 = None
        p2 = head
        while(p2 is not None):
            tmp = p2.next
            p2.next = p1
            p1 = p2
            p2 = tmp
        return p1

Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

迭代法

复杂度

时间 O(N) 空间 O(1)

思路

技巧在于记录下这么几个变量:dummyHead、子链反转前的头节点,子链反转前头节点前面一个节点,子链反转过程中的当前节点,子链反转过程中的下一个节点,这五个指针。先跳过前m个节点,然后初始化好这五个指针后,用I中的方法反转链表。完成了第n个节点的反转后,将子链反转前的头节点的next设为子链反转过程中的下一个节点,将子链反转前头节点前面一个节点的next设为子链反转过程中的当前节点。由于设置了dummyhead,我们所有的反转操作都是不包含头节点的,所以直接返回dummyhead的next就行了。

注意

跳过前m个节点的for循环要从1开始,因为我们要保证head是第m-1个元素,如果m=1则不动。

代码

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        for(int i = 1 ; i < m; i++){
            head = head.next;
        }
        ListNode headOfSubList = head.next;
        ListNode nodeBeforeHead = head;
        ListNode nextNode = head.next.next;
        ListNode currNode = head.next;
        for(int i = m; i < n ; i++){
            ListNode tmp = nextNode.next;
            nextNode.next = currNode;
            currNode = nextNode;
            nextNode = tmp;
        }
        headOfSubList.next = nextNode;
        nodeBeforeHead.next = currNode;
        return dummy.next;
    }
}
    原文作者:ethannnli
    原文地址: https://segmentfault.com/a/1190000003707458
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞