剑指Offer刷题(3)

来源:互联网 发布:网页调用淘宝客户端 编辑:程序博客网 时间:2024/04/28 03:07

<span style="font-family: arial, STHeiti, 'Microsoft YaHei', 宋体;">题目描述</span>

输入一个链表,从尾到头打印链表每个节点的值。 
输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头
思路:
我们可以通过一个vector,然后不断在开始处其中插入链表的表头元素。
代码如下:
/***  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> v;    while(head!=NULL)    {    v.insert(v.begin(),head->val);    head=head->next;    }        return  v;                    }};
最佳代码:代码思路借助栈,遍历的时候入栈,由于数据结构中栈的特点是先进后出,所以遍历的过程中压栈,推栈,完了弹栈加到ArrayList中。有两个容易出错的地方:第一,第一次测试用例,{}返回[ ],null是null,而[ ]是new ArrayList()但是没有数据。第二,遍历stack用的方法是!stak.isEmpty()方法,而不是for循环size遍历。
/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(struct ListNode* head)    {//利用栈的逆序输出特性               stack<int> stack;        vector<int> vector;        struct ListNode *p = head;        if (head != NULL)         {            stack.push(p->val);            while((p=p->next) != NULL)            {                stack.push(p->val);            }            while(!stack.empty())            {                vector.push_back(stack.top());                stack.pop();            }        }        return vector;    }         };



0 0