单链表面试题几乎是面试的必考之题;

对于单链表从头到尾打印与单链表的逆置不是一回事。

单链表的从头到尾打印是打印出链表的数据。(即数据是从尾向前输出);


一、单链表从头到尾打印:

/***structListNode{*intval;*structListNode*next;*ListNode(intx):*val(x),next(NULL){*}*};*/classSolution{public:vector<int>printListFromTailToHead(structListNode*head){vector<int>result;stack<ListNode*>node;structListNode*newhead=head;while(newhead!=NULL){node.push(newhead);newhead=newhead->next;}while(!node.empty()){newhead=node.top();result.push_back(newhead->val);node.pop();}returnresult;}};

二、单链表的逆置

/*structListNode{intval;structListNode*next;ListNode(intx):val(x),next(NULL){}};*/classSolution{public:ListNode*ReverseList(ListNode*pHead){if(pHead==NULL)returnNULL;ListNode*cur=pHead;ListNode*newHead=NULL;while(cur){ListNode*tmp=cur;cur=cur->next;tmp->next=newHead;newHead=tmp;}returnnewHead;}};