阅读背景:

3.从尾到头打印链表+链表的基本操作

来源:互联网 

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/

// 头插思路:
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector <int> value;
        while (head != NULL)
        {
            value.insert(value.begin(), head->val);
            if (head->next != NULL)
            {
                head = head->next;
            }
            else
                break;
        }
        return value;
    }
};
// 栈思路:
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> value;
        ListNode *p=NULL;
        p=head;
        stack<int> stk;
        while(p!=NULL){
            stk.push(p->val);
            p=p->next;
        }
        while(!stk.empty()){
            value.push_back(stk.top());//栈顶的元素
            stk.pop();//将栈顶的元素弹出,栈顶指针指向下一个元素
        }
        return value;
    }
};
// 翻转思路:
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> value;
        ListNode *p=NULL;
        p=head;
        while(p!=NULL){
            value.push_back(p->val);
            p=p->next;
        }
        reverse(value.begin(),value.end()); 
        return value;
    }
};
// 递归思路:
class Solution {
public:
    vector<int> value;
    vector<int> printListFromTailToHead(ListNode* head) {
        ListNode *p=NULL;
        p=head;
        if(p!=NULL){
            if(p->next!=NULL){
                printListFromTailToHead(p->next);
            }
            value.push_back(p->val);
        }
        return value;
    }
};
/*



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: