两种方法实现:输入一个链表,从尾到头打印链表每个节点的值

来源:互联网 发布:不用网络调频收音机 编辑:程序博客网 时间:2024/06/11 09:03

在《剑指offer》书中第五题:从尾到头打印链表每个节点的数值。其中提到的方法是通过借助容器vector和配接器stack共同完成;然而,碰巧的是前几日在刷LeetCode的时候,无意中发现一处用到了STL中的翻转函数reverse(),它接受两个BidirectionalIterator型的迭代器first和last,迭代器遍历范围为[first,last)。觉得这个函数特别有用,因此特意在牛课网上找了这个题目再次测试了一遍,结果也通过了测试。利用reverse()函数,代码更简洁,而且只利用了容器vector,无需借助配接器stack。下面给出这两种方法的函数代码。

方法一:原《剑指offer》中的示例代码,利用了vector和stack。

vector<int> printListFromTailToHead(struct ListNode* head) {        vector<int> result;        stack<struct ListNode*> nodes;        struct ListNode* pNode=head;        while(pNode!=NULL){            nodes.push(pNode);            pNode=pNode->next;        }        while(!nodes.empty()){            pNode=nodes.top();            result.push_back(pNode->val);            nodes.pop();        }        return result;

方法二:利用reverse()函数和容器vector。

vector<int> printListFromTailToHead(struct ListNode* head) {        vector<int> result;        struct ListNode* pNode=head;        while(pNode!=NULL){            result.push_back(pNode->val);            pNode=pNode->next;        }        reverse(result.begin(),result.end());// applying reverse()        return result;    }
0 0
原创粉丝点击