JZ6 从尾到头打印链表
描述
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{1,2,3}的链表如下图:
返回一个数组为[3,2,1]
0 <= 链表长度 <= 10000
示例1
输入:
{1,2,3}
返回值:
[3,2,1]
示例2
输入:
{67,0,24,58}
返回值:
[58,24,0,67]
我的解答:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> vlist;
void printLNode(ListNode* h){
if(h->next != NULL){
printLNode(h->next);
}
vlist.push_back(h->val);
}
vector<int> printListFromTailToHead(ListNode* head) {
if(head ->next!= NULL && head != NULL)
printLNode(head);
return vlist;
}
};
思路:①本题是将顺序的表进行逆序输出,通过递归程序先寻找到表末,然后进行输出
其余思路:②设计栈进行操作③顺序输入再逆序输出(翻转reverse)
补充:
①精简版:
class Solution {
public:
vector<int> vlist;
vector<int> printListFromTailToHead(ListNode* head) {
ListNode *p = head;
if(p != NULL){
if(p ->next!= NULL)
printListFromTailToHead(p->next);
vlist.push_back(p->val);
}
return vlist;
}
};