Topic DescriptionEnter a list that prints the value of each node in the list from the end. Online programming chain interview: Print a list from the end of the head
Enter a description:
Table header entered as a list
Output Description:
Table header for "New linked list" that needs to be printed
Analysis:This problem seems to be relatively simple, but in fact there are a lot of ideas can be solved. Here's a simple summary.
Idea 1:Traversing the list, insert each element into the vector container using the header interpolation code as follows:
Vector<int> printlistfromtailtohead (struct listnode* head) {
vector<int> v;
while (head!= NULL)
{
V.insert (V.begin (), head->val);
Head = head->next;
}
return v;
}
Idea 2:With the help of stacks, traversal of the time into the stack, because the data structure of the stack is the characteristics of advanced, so the process of traversing the stack, push the stack, the stack added to the ArrayList. The code is as follows:
Vector<int> printlistfromtailtohead (struct listnode* head) {
//The reverse output feature of stack is
stack<int> stack;
Vector<int> Vector;
struct ListNode *p = head;
if (head!= NULL) {
stack.push (p->val);
while ((P=p->next)!= NULL) {
stack.push (p->val);
}
while (!stack.empty ()) {
vector.push_back (stack.top ());
Stack.pop ();
}
return vector;
Idea 3:Using the vector reverse iterator of the container, the code is as follows:
Vector<int> printlistfromtailtohead (struct listnode* head) {
vector<int> v;
ListNode *p = head;
while (P!= nullptr) {
v.push_back (p->val);
p = p->next;
}
The reverse iterator creates a temporary object return
vector<int> (V.rbegin (), V.rend ());
Idea 4:Using recursive methods, the code is as follows:
Vector<int> printlistfromtailtohead (struct listnode* head) {
vector<int> vec;
if (!head) return
VEC;
Printlistfromtailtohead (head->next);
Vec.push_back (head->val);
return VEC;
}
Note: recursion vs. stack Two versions: The above recursive code looks simple, but there is a problem: When the list is very long, it will cause the function call is very deep, which may cause the function call stack overflow. Explicit use of the stack based on the loop implementation of the code is better robustness.
The complete code can refer to the sword finger offer--> face question 5 Print the chain list from the end head
reference materials:Sword refers to an offer interview question: 4. Print a list from the end of the head
[Sword refers to offer] 7. Print a list from the end of the head