关于反转链表的问题

来源:互联网 发布:看澳洲股市软件 编辑:程序博客网 时间:2024/05/22 14:59

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

思路:1、最先想到栈的结构,符合先进后出的特点;

2、递归与栈的关系,联想到使用递归的方法来实现(递归结构好好理解一下,感觉自己以前其实没有理解很清楚)

3、用vector从头端插入的思想来解决

代码如下:

思路1的代码,利用栈的结构

int ReverseList(ListNode *head){stack<int> stack;ListNode *p;p = head->next;while (p != NULL){stack.push(p->val);p = p->next;}while (!stack.empty()){cout<<stack.top();stack.pop();}return 0;}

思路2的代码:

#include<iostream>#include<iomanip>#include <iostream>#include <stdio.h>#include <string.h>#include <list>#include<vector>#include <cstdio>#include <iostream>#include <stack>#include <queue>using namespace std;struct ListNode{int val;ListNode *next;ListNode(int x) :val(x), next(nullptr){}};void helper(ListNode* head, vector<int> &result){if (head){if (head->next){helper(head->next, result);//注意好好理解这个地方,当最后一次不符合if条件时,执行result.后面的内容。执行完毕后,其实是返回到上一次执行到这里的代码,继续执行result.后面的内容。这里我之前一直没太理解,有空好好研究一下递归的调用过程。与函数调用时现场保护的原则应该是有关系的}//if  result.push_back(head->val);}//if  int temp = 0;}vector<int> printListFromTailToHead(ListNode* head) {vector<int> result;// 递归实现  helper(head, result);return result;}int main(){ListNode* root = new ListNode(1);ListNode* node1 = new ListNode(2);ListNode* node2 = new ListNode(3);ListNode* node3 = new ListNode(4);ListNode* node4 = new ListNode(5);root->next = node1;node1->next = node2;node2->next = node3;node3->next = node4;vector<int> result = printListFromTailToHead(root);for (int i = 0; i < result.size(); ++i){cout << result[i] << endl;}//for  return 0;}
思路3的代码:很巧妙利用了每次在vector前端插入,只是我觉得这样的开销可能会比较大啊~~

vector<int> printListFromTailToHead(ListNode* head) {vector<int> result;ListNode* p = head;while (p){result.insert(result.begin(), p->val);p = p->next;}//while  return result;}
【参考】http://blog.csdn.net/sunnyyoona/article/details/12858771

0 0