---JZ6 从尾到头打印链表
- 题目
- 题解(192)
- 讨论(2k)
- 排行
简单 通过率:28.70% 时间限制:1秒 空间限制:64M
知识点链表
描述
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{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> printListFromTailToHead(ListNode* head) {
ListNode * newhead=NULL;
ListNode * temp=NULL;
int len=0;
while(head!=NULL){
temp=head;
head=head->next;
temp->next=newhead;
newhead=temp;
len++;
}
vector<int> s(len);
int i=0;
while(newhead!=NULL){
s[i++]=newhead->val;
newhead=newhead->next;
}
return s;
}
};
--就地逆转
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode * beg=NULL;
ListNode * end=NULL;
if(head==NULL){
vector<int> s(0);
return s;
}else{
beg=head;
end=head->next;
int len=0;
while(end!=NULL){
beg->next=end->next;
end->next=head;
head=end;
end=beg->next;
len++;
}
vector<int> s(len+1);
int i=0;
while(head!=NULL){
s[i++]=head->val;
head=head->next;
}
return s;
}
}
};