# Learning of data structure and algorithm -- printing the linked list from the end to the end in "sword finger Offer"

Posted by stereofrog on Thu, 13 Feb 2020 22:50:00 +0100

## Learning of data structure and algorithm -- printing the linked list from the end to the end in "sword finger Offer"

### Portal: General Catalogue of sword finger Offer

Time: February 6, 2020
Because of the epidemic, school was delayed again. Then I'll brush the questions at home! )

Title:
Enter a linked list and return an ArrayList from the end to the end of the list.

Java code:

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

/**
* Enter a linked list and return an ArrayList from the end to the end of the list.
*/
class ListNode{
int val;
ListNode next=null;
ListNode(int val){
this.val=val;
}
public void setNext(ListNode node){
this.next=node;
}
}
/**
*Method 1.1: use the first in and last out of stack
* Time complexity: O(N)
* Running time: 17ms
* Occupied memory: 9480k
*/
Stack<Integer> temp=new Stack<>();
ArrayList<Integer> result=new ArrayList<>();

while (listNode!=null){
temp.push(listNode.val);
listNode= listNode.next;
}

while(!temp.empty()){
}
return result;
}

/**
* Method 1.2: using recursion and the "stack" of the system
* Recursive equation: T(N)=T(N-1)+O(1)
* Time complexity: O(N)
* Running time: 21ms
* Occupied memory: 9368k
*/
ArrayList<Integer> result_2=new ArrayList<>();
if (listNode!=null){//When it's written accidentally, it goes into a dead cycle
// System.out.println(listNode.val); / / debugging
}
return result_2;
}

/**
* Method 2: use the add method of ArrayList to insert new elements to the front all the time, which is inefficient
* Time complexity: O(N ²)
* Running time: 28ms
* Occupied memory: 9212k
*/
ArrayList<Integer> result_3=new ArrayList<>();
while(listNode!=null){
result_3.add(0,listNode.val);//Looking at the source code, we can see that this method is to copy one by one
// Insert the position and the array elements after it, to the next cell, and the complexity of inserting to the front is O(n)
listNode=listNode.next;
}
return result_3;
}
public static void main(String[] args) {
ListNode first=new ListNode(2);
ListNode second=new ListNode(3);
first.setNext(second);
System.out.println(test);
}
}
```

C++

```/*Enter a linked list and return an ArrayList from the end to the end of the list*/
#include <iostream>
#include<vector>
#include <stack>
using namespace std;

struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
/**
Press in stack:
Time complexity: O(N)
Running time: 4ms; occupied memory: 484k
*/
vector<int> result;
if (head == NULL) return result;
stack<int> temp;
}
while (!temp.empty()) {
result.push_back(temp.top());
temp.pop();//The pop of c + + does not return a value
}
return result;
}
};
int main() {
ListNode first(1);
ListNode second(2);
ListNode third(3);
first.next = &second;
second.next = &third;
Solution so;  