算法通关村第二关——终于学会链表反转

1.借助虚拟结点(空结点)实现反转

算法通关村第二关——终于学会链表反转_第1张图片

 

public static ListNode reverseList(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;
    }

2.不借助虚拟结点直接反转,双指针

算法通关村第二关——终于学会链表反转_第2张图片

public static ListNode reverseList2(ListNode head){
        ListNode prev = null;
        ListNode cur = head;

        while (cur != null){
            ListNode next = cur.next;//cur.next动了所以要存一下
            cur.next = prev;
            prev = cur;
            cur =next;
        }

        return prev;
    }

 3.递归反转

public static ListNode reverseList3(ListNode head){
        if (head == null||head.next == null) {
            return head;
        }

        ListNode newHead = reverseList3(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

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