从尾到头打印链表(五种方法包括链表翻转、递归、栈、容器逆序)

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vectorintv;
    void dg(ListNode* head)
        {
        if(head==NULL)return;
        dg(head-next);
        v.push_back(head-val);
    }
    vectorint printListFromTailToHead1(ListNode* head) {
        dg(head);
        return v;
    }
    vectorint printListFromTailToHead2(ListNode* head) {
        stackints;
        vectorintv;
        while(head!=NULL)
            {
            s.push(head-val);
            head=head-next;
        }
        while(!s.empty())
            {
            v.push_back(s.top());
            s.pop();
        }
        return v;
    }
    vectorint printListFromTailToHead3(ListNode* head) {
        vectorintv;
        while(head!=NULL)
            {
            v.push_back(head-val);
            head=head-next;
        }
        reverse(v.begin(),v.end());
        return v;
    } 
    vectorint printListFromTailToHead4(ListNode* head) {
        vectorintv;
        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;
    }
    vectorint printListFromTailToHead(ListNode* head) {
        vectorintv;
        ListNode*phead=new ListNode(-1);
        ListNode*p=head;
        while(p)
        {
            ListNode*pnext=p-next;
            p-next=phead-next;
            phead-next=p;
            p=pnext;
        }
        phead=phead-next;
        while(phead)
        {
            v.push_back(phead-val);
            phead=phead-next;
        }
        return v;
    }  
};

最新回复(0)
/jishu8r_2F6VSG7kX32ATaTpNKZZvy9tiqdxutXN2xaNA_3D_3D4488736
8