Search This Blog

Monday, June 13, 2011

Print a singly linked list reversely

For a singly linked list, you can only access the list element from the head.  At the first glance, it seems difficulty printing the element reversely (the tail first).  However if you know recursive, the problem becomes quite easy. Here is how to solve this problem in Java:

public class ListUtil {
    public static <T> void  reversePrint(List<T> list) {
        if (list == null || list.isEmpty()) {
            System.out.println("empty list");
        } else {
            Iterator<T> iter = list.iterator();
            reversePrint(iter);
        }
    }
   
    private static <T> void reversePrint(Iterator<T> iter) {
        if (iter.hasNext()) {
            T data = iter.next();
            reversePrint(iter);
            System.out.println(data);
        }
    }
}

No comments:

Post a Comment