Classical algorithm problem - the foundation - print the list from the tail to the head

Problem Description

Description Title
input a linked list, returns a list according to the order of the tail from the head of ArrayList.

Required
time limit: 1 second
space constraints: 32768K

Methods Prototype

public ArrayList<Integer> printListFromTailToHead(ListNode listNode)
public class ListNode {
 int val;
 ListNode next = null;
}

Problem-solving ideas

If it is doubly linked list, then this topic would be too simple, get the iterator can traverse directly from the tail. However, it can be seen from the prototype method Prototype ListNode given, this problem is singly linked list .
The default list can traverse from beginning to end way, the requirements of the subject from the tail to the head in the opposite requirements. So the key to this question then becomes how to reverse the traverse path , it will naturally think of using a last-out stack structure.
Specifically, we can:

  • Prepare a stack of extra
  • For singly linked list traversal from start to finish
  • Not to traverse a linked list node, list node on the stack
  • After traversed list, remove the stack elements sequentially and printed until the stack is empty

The following figure shows the move this process:

It is noted that in the above solution stack only logical concept , the actual programming may replace it with a list, an array.

The relevant code

JAVA version

Because the STL have a ready stack data structure of java and C ++ standard package, we can directly use the following code to achieve the java:

package com.shellmad;

import java.util.ArrayList;
import java.util.Stack;

public class Solution {

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> result = new ArrayList<>();

        // 遍历链表,入栈
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }

        // 出栈
        while (stack.size() != 0) {
            result.add(stack.pop());
        }

        return result;
    }
}

class ListNode {
    public int val;
    public ListNode next = null;
}

C ++ version

The following is a C ++ implementation:

#include <vector>
using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};

class Solution {
public:
    static vector<int> printListFromTailToHead(ListNode* head)
    {
        vector<int> ArrayList;
        ListNode* pCur = head;
        ListNode* pTail = NULL;
        while (head != pTail)
        {
            pCur = head;
            while (pCur->next != pTail)
            {
                pCur = pCur->next;
            }
            ArrayList.push_back(pCur->val);
            pTail = pCur;
        }
        return ArrayList;
    }
};

Guess you like

Origin www.cnblogs.com/shellmad/p/11641009.html