单链表面试题几乎是面试的必考之题;
对于单链表从头到尾打印与单链表的逆置不是一回事。
单链表的从头到尾打印是打印出链表的数据。(即数据是从尾向前输出);
一、单链表从头到尾打印:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> result;
stack< ListNode*> node;
struct ListNode* newhead=head;
while(newhead!=NULL)
{
node.push(newhead);
newhead=newhead->next;
}
while(!node.empty())
{
newhead=node.top();
result.push_back(newhead->val);
node.pop();
}
return result;
}
};
二、单链表的逆置
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL)
return NULL;
ListNode* cur=pHead;
ListNode* newHead=NULL;
while(cur)
{
ListNode* tmp=cur;
cur=cur->next;
tmp->next=newHead;
newHead=tmp;
}
return newHead;
}
};
转载于:https://blog.51cto.com/10738432/1828329