链表反转问题

链表反转常用的两种方式

1.建立虚拟头结点辅助反转

链表反转问题_第1张图片

Java 实现

    public static ListNode reverseListByDummyNotCreate(ListNode head) {
        ListNode ans = new ListNode(-1);
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = ans.next;
            ans.next = cur;
            cur = next;
        }
        return ans.next;
    }

python实现

    def reverseList1(self, head):
        if not head or not head.next:  # 如果链表为空,或者只有一个节点
            return head
        ans = ListNode(-1)
        cur = head

        while cur:
            next = cur.next
            cur.next = ans.next
            ans.next = cur
            cur = next
        return ans.next

2.直接操作链表实现反转

链表反转问题_第2张图片

Java实现

    public static ListNode reverseListSimple(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

python实现

 def reverseList2(self, head):
        if not head or not head.next:  # 如果链表为空,或者只有一个节点
            return head
        cur = head.next
        head.next = None
        while cur:
            next = cur.next
            cur.next = head
            head = cur
            cur = next
        return head

你可能感兴趣的:(算法打卡,链表,数据结构)