code4offer-3 从尾到头打印链表

从尾到头打印链表

问题描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

分析

链表只能顺序访问,但要求逆序地返回链表中的元素

  1. 遍历链表存到临时空间(栈或数组都行),再逆序输出到最终结果
  2. 反转链表,遍历链表到最终结果

临时空间

遍历链表,将数据插入栈,逆向遍历临时空间,将数据插入最终结果数组

C++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 使用vector作为临时空间
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> tmp;
vector<int> result;
if (head == NULL) return result;
ListNode* tmpHead = head;
while (tmpHead != NULL) {
tmp.push_back(tmpHead->val);
tmpHead = tmpHead->next;
}

int len = tmp.size();
for(int i = len - 1; i >=0; --i) {
result.push_back(tmp[i]);
}

return result;
}

// 使用stack作为临时空间
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> tmp;
vector<int> result;
if (head == NULL) return result;
ListNode* tmpHead = head;
while (tmpHead != NULL) {
tmp.push(tmpHead->val);
tmpHead = tmpHead->next;
}

while (!tmp.empty()) {
result.push_back(tmp.top());
tmp.pop();
}
return result;
}

Java版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
while (listNode != null) {
tmp.add(listNode.val);
listNode = listNode.next;
}
int len = tmp.size();
for(int i = len-1; i >= 0; --i) {
result.add(tmp.get(i));
}

return result;
}

反转单链表

先reverse单链表,再遍历单链表,将数据插入最终结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
vector<int> printListFromTailToHead(ListNode* head) {
if (head == NULL || head->next == NULL) return {};
ListNode* pre = NULL;
ListNode* cur = head;

while (cur != NULL) {
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}

head = pre;

vector<int> result;
while (head != NULL) {
result.push_back(head->val);
head = head->next;
}

return result;
}