单链表面试题(二)从头到尾打印单链表
单链表面试题几乎是面试的必考之题;
乌海网站建设公司创新互联公司,乌海网站设计制作,有大型网站制作公司丰富经验。已为乌海近1000家提供企业网站建设服务。企业网站搭建\外贸网站建设要多少钱,请找那个售后服务好的乌海做网站的公司定做!
对于单链表从头到尾打印与单链表的逆置不是一回事。
单链表的从头到尾打印是打印出链表的数据。(即数据是从尾向前输出);

一、单链表从头到尾打印:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector printListFromTailToHead(struct ListNode* head) {
vector 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;
}
};
分享标题:单链表面试题(二)从头到尾打印单链表
文章分享:http://www.jxjierui.cn/article/jgchec.html


咨询
建站咨询
