【面试题】剑指offer 5

来源:互联网 发布:js文件调用java代码 编辑:程序博客网 时间:2024/05/18 01:21

输入一个链表的头结点,从尾到头打印链表

#include<iostream>#include<assert.h>using namespace std;class ListNode{public:ListNode(const int & x):_value(x),_next(NULL){}int _value;ListNode* _next;};class List{public:List():head(NULL){}void pushTail(const int& key){if(head==NULL)head=new ListNode(key);else{ListNode* node=head;while (node->_next!=NULL){node=node->_next;}node->_next=new ListNode(key);}}void printTail(ListNode* head){if(head!=NULL){if(head->_next!=NULL){//printTail();printTail(head->_next);}printf("%d ",head->_value);}printf("\n");}public:ListNode* head;};int main(){List list;list.pushTail(1);list.pushTail(2);list.pushTail(3);list.pushTail(4);list.pushTail(5);ListNode* node=list.head;    list.printTail(node);system("pause");return 0;}


0 0