Learn Algorithms with Me Series 5---Print Linked Lists from End to End

 
 

1. Title Description Input a linked list and print the value of each node of the linked list from end to beginning.

2. Algorithm Analysis There are two ways to solve this problem. One way is to use recursion, the first node of the linked list is recursive until the last node is added to the list first.

The second way is to use the particularity of Stack, first in, last out, first add all nodes to the stack from the beginning to the end, and then pop out of the stack in turn.

3. Code example (1) Recursion

ArrayList<Integer> mList = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode){
        if(null != listNode)
    {
        if(null != listNode.next)
        {
        mList = printListFromTailToHead(listNode.next);
        }
            
            mList.add(new Integer(listNode.val));
    }
        
    return mList;
}

(2) Use Stack

public ArrayList<Integer> printListFromTailToHead(ListNode listNode){ 
        ArrayList<Integer> mList = new ArrayList<Integer>();
        ListNode head = listNode;
        Stack<Integer> stack = new Stack<Integer>();
    
        while(null != head)
        {
            stack.push(new Integer(head.val));
            head = head.next;
        }
        
        while(!stack.isEmpty())
        {
            mList.add(stack.pop());
        }
        
        return mList;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325721873&siteId=291194637