题目描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回),这个头结点是存数据的。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
代码1:
我自己第一次写是用的栈后进先出的这个特性来实现的。
/**
* 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) {
vector<int> v;
if(head==NULL) return v;
stack<int> sta;
while(1){
sta.push(head->val);
if(head->next==NULL) break;
head=head->next;
}
while(sta.empty()!=true){
v.push_back(sta.top());//切记sta.pop()删除后不返回
sta.pop();
}
return v;
}
};
切记sta.pop()删除后不返回,用sta.top先返回栈顶元素,在用sta.pop()删除栈顶元素。
代码2:
题解代码用的是vector的插入特性。
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int>v;
while(head){
v.insert(v.begin(),head->val);
head=head->next;
}return v;
}
};
v.insert(p,t)(将t插入到p的前面)t表示类型为T(如vector)的值,p表示迭代器。
例如:v.insert(v.begin()+2,5) 在第三个位置插入5 。
代码3:
头插法,他的头节点head存了第一个数据,所以我新开了一个空间。用来充当不存数据的头结点。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode*newl=new ListNode;
newl->next=NULL;
ListNode*p=head;
ListNode*t=NULL;
while(p){
t=p->next;
p->next=newl->next;
newl->next=p;
p=t;
}
return newl->next;}
};