- 06 从尾到头打印链表
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解题思路:【c++】(1)遍历链表得到链表长度,并将所有数值存入一个数组,再反向搜索存入另一个数组;(2)利用栈,遍历链表将所有元素压入栈,在将元素从栈中拿出存入数组。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
//solution 1
// int count = 0;
// ListNode* node = head;
// vector<int> num, num_reverse; //默认为[]
// while (node != NULL){
// count ++;
// num.push_back(node->val);
// node = node->next;
// }
// // cout<< num.size()<<endl;
// if (count >0){
// for(int i = 0; i< count; ++i){
// num_reverse.push_back(num[count -1-i]);
// }
// }
// return num_reverse;
//solution 2
stack<int> s;
vector<int> num;
while (head != NULL){
s.push(head->val);
head = head->next;
}
// cout << s.size()<<endl;
while(!s.empty()){
num.push_back(s.top());
s.pop();
}
return num;
}
};
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
num =[]
num_reverse = []
count = 0
while(head):
count =count+1
num.append(head.val)
head = head.next
if count>0:
for i in range(count):
num_reverse.append(num[count-1-i])
return num_reverse