从尾到头打印链表(含翻转链表两种方法)

来源:互联网 发布:淘宝网成唯识论直解 编辑:程序博客网 时间:2024/06/09 15:23
/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> a;    //方法一:递归(自底向上)    vector<int> printListFromTailToHead1(ListNode* head) {        if(head!=NULL)            {            printListFromTailToHead(head->next);            a.push_back(head->val);        }        return a;    }    //方法二:栈    vector<int> printListFromTailToHead2(ListNode* head) {        vector<int>v;        stack<int>s;        while(head)            {            s.push(head->val);            head=head->next;        }        while(s.size())            {            v.push_back(s.top());            s.pop();        }        return v;    }        //方法三:逆序    vector<int> printListFromTailToHead3(ListNode* head) {        vector<int>v;        while(head)            {            v.push_back(head->val);            head=head->next;        }        reverse(v.begin(),v.end());        return v;    }    //方法四:翻转链表1    vector<int> printListFromTailToHead4(ListNode* head) {        vector<int>v;        ListNode* p=head;        ListNode* pre=NULL;        while(p)            {            ListNode* pnext=p->next;            p->next=pre;            pre=p;            p=pnext;        }        while(pre)            {            v.push_back(pre->val);            pre=pre->next;        }        return v;    }       //方法五:翻转链表2    vector<int> printListFromTailToHead(ListNode* head) {        vector<int>v;        ListNode* ahead=new ListNode(-1);        ahead->next=head;        ListNode*p=NULL;        if(head==NULL)return v;        while(head->next)            {            p=head->next;            head->next=p->next;            p->next=ahead->next;            ahead->next=p;        }        head=ahead->next;        while(head)            {            v.push_back(head->val);            head=head->next;        }        return v;    }};

原创粉丝点击