206 - 反转链表 - python + Java

91 阅读1分钟

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:你可以迭代或递归地反转链表。你能否用两种方法解决这道题?


  • 辅助数组法:首先遍历链表中的元素,并使用额外的数组保存访问的节点值,然后将数组反转,最后使用反转后的数组构建新的链表并返回链表头。

    时间复杂度 O ( N ) O(N) O(N)

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head: return None

        r = []
        cur = head
        while cur:
            r.append(cur.val)
            cur = cur.next

        r.reverse()
        
        new = ListNode(-1)
        cur = new
        for i in r:
            cur.next = ListNode(i)
            cur = cur.next

        return new.next
  • 直接反转:设置new作为反转链表的头结点,然后依次访问给定链表中的元素,将其不断的插入到new前,并不断的更新new,最后返回表头new即可

    时间复杂度 O ( N ) O(N) O(N)

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head: return None

        new = None
        cur = head
        while cur:
            node = ListNode(cur.val)
            node.next = new
            new = node
            cur = cur.next

        return new
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null){
            return null;
        }

        ListNode node = null;
        ListNode cur = head;
        //ListNode temp = null;
        while(cur != null){
            ListNode temp = new ListNode(cur.val);
            temp.next = node;
            node = temp;
            cur = cur.next;
        }

        return node;
    }
}
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        nextNode = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return nextNode