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

建立虚拟头结点辅助反转

public ListNode reverseList(ListNode head) {
        if(head == null)
            return null;
        ListNode dummyNode, cur, next;
        dummyNode = new ListNode(-1);
        cur =  head;
        while(cur != null)
        {
            next = cur.next;
            cur.next = dummyNode.next;
            dummyNode.next = cur;
            cur = next;
        }
        return dummyNode.next;
    }

直接操作链表实现反转

public ListNode reverseList(ListNode head) {
        if(head == null)
            return null;
        ListNode pre, cur, next;
        pre = next = null;
        cur = head;
        while(cur != null)
        {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

递归实现反转

public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

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