从尾到头打印链表

来源:互联网 发布:em算法 q函数 编辑:程序博客网 时间:2024/05/17 01:47

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

输入描述:
输入为链表的表头

输出描述:


输出为需要打印的“新链表”的表头

思路一:(利用链表的翻转,然后直接存储!!!)

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(struct ListNode* head) {        vector<int> A;        struct ListNode *s = NULL;        struct ListNode *q = NULL;        s = head;        head = NULL;        while(s != NULL)            {            q = s;            s = s->next;            q->next = head;            head = q;        }        q = head;        while(q != NULL)            {            A.push_back(q.val);            q = q->next;        }        return A;    }};

思路二:(利用栈)

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(struct ListNode* head) {        vector<int> vector;        stack<int> stack;        struct ListNode *p = head;        while(p != NULL)            {            stack.push(p->val);            p = p->next;        }        while(!stack.empty())            {            vector.push_back(stack.top());            stack.pop();        }        return vector;    }};
其中借用:

vector<int> vector;stack<int> stack;<pre name="code" class="cpp">vector.push_back(stack.top());stack.pop();


0 0
原创粉丝点击