面试题:从尾到头打印链表
题目:输入一个链表的头结点,从尾到头反过来打印出每个节点的值。
方法1:使用栈
/*链表节点定义如下:structListNode{int_data;ListNode*_next;};*/voidPrintListTailToHead(ListNode*phead){assert(phead);stack<ListNode*>s;ListNode*cur=phead;while(cur){s.push(cur);cur=cur->_next;}while(!s.empty()){cout<<s.top()->_data<<"";s.pop();}cout<<endl;}
方法2:递归
voidPrintListTailToHead(ListNode*phead){if(phead==NULL){return;}PrintListTailToHead(phead->_next);cout<<phead->_data<<"";}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。