Print singly linked list reversely

Print a singly-linked list backwards, in constant space and linear time.

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}

public void printList(ListNode head) {
    ListNode cur = head;
    while(cur != null) {
        System.out.print(cur.val);
        cur = cur.next;
    }
}

public void reverseList(ListNode head) {
    ListNode prev=null;
    ListNode cur=head;
    while(cur != null) {
        ListNode temp = cur.next;
        cur.next = prev;
        prev = cur;
        cur = temp;
    }
    return prev;
}

public void printListReversely(ListNode head) {
    if (head == null) return;
    ListNode reverseHead = reverseList(head);
    printList(reverseHead);
    head = reverseList(reverseHead);
}

results matching ""

    No results matching ""