206 Reverse Linked List

Reverse a singly linked list.

analysis

code

public ListNode reverseList(ListNode head) {
        Stack<ListNode> s = new Stack<ListNode>();

        //cornercase
        if(head == null) return head;

        ListNode pointer = head;

        //push all node into stack
        while(pointer != null) {
            s.push(pointer);
            pointer = pointer.next;
        }

        //pop all node out of stack
        //dealing with header
        if(!s.isEmpty()) {
            head = s.pop();
            pointer = head;
        }
        //other nodes
        while(!s.isEmpty()) {
            pointer.next = s.pop();
            pointer = pointer.next;
        }
        //last node
        pointer.next = null;

        return head;
    }

better code

public ListNode reverseList(ListNode head) {

        //cornercase
        if(head == null) return head;

        //first node
        ListNode last = head;
        ListNode current = last.next;
        last.next = null;

        while(current != null) {
            //store next of current
            ListNode temp = current.next;
            //change current next reversely
            current.next = last;

            //move
            last = current;
            current = temp;
        }

        return last;

    }

results matching ""

    No results matching ""