剑指offer 从尾到头打印链表
2016-03-08 20:54
387 查看
题目描述:
输入一个链表,从尾到头打印链表每个节点的值。
思路:
很多方法,最有用的就是真的实现一个链表然后进行操作。
一开始我的做法是每次插入先从头结点遍历到尾结点,然后进行插入操作,但是TLE了,最后发现其实插入操作只需要O(1),即用一个新的指针维护尾部节点。递归方式插入还是O(n)…
输入一个链表,从尾到头打印链表每个节点的值。
思路:
很多方法,最有用的就是真的实现一个链表然后进行操作。
一开始我的做法是每次插入先从头结点遍历到尾结点,然后进行插入操作,但是TLE了,最后发现其实插入操作只需要O(1),即用一个新的指针维护尾部节点。递归方式插入还是O(n)…
#include <cstdio> #include <stack> using namespace std; typedef struct Node{ int val; Node *next; Node(int val) : val(val), next(NULL) {} } *pNode; class List{ private: pNode Head; pNode Tail; void Recursion_Insert_Node(pNode *node, int x); void Non_Recursion_Insert_Node(pNode *node, int x); void Recursion_Traverse_List(pNode node); void Non_Recursion_Traverse_List(pNode node); void Recursion_Delete_List(pNode node); void Non_Recursion_Delete_List(pNode node); public: void Recursion_Insert_Node(int x); void Non_Recursion_Insert_Node(int x); void Recursion_Traverse_List(); void Non_Recursion_Traverse_List(); List(); ~List(); }; void List::Recursion_Insert_Node(pNode *node, int x){ if(*node == NULL) *node = new Node(x); else Recursion_Insert_Node(&((*node)->next), x); } void List::Recursion_Insert_Node(int x){ Recursion_Insert_Node(&this->Head, x); } void List::Non_Recursion_Insert_Node(pNode *node, int x){ if(*node == NULL){ *node = new Node(x); this->Tail = *node; } else{ this->Tail->next = new Node(x); this->Tail = this->Tail->next; } } void List::Non_Recursion_Insert_Node(int x){ Non_Recursion_Insert_Node(&this->Head, x); } void List::Recursion_Traverse_List(){ Recursion_Traverse_List(this->Head); } void List::Recursion_Traverse_List(pNode node){ if(node){ Recursion_Traverse_List(node->next); printf("%d\n", node->val); } } void List::Non_Recursion_Traverse_List(){ Non_Recursion_Traverse_List(this->Head); } void List::Non_Recursion_Traverse_List(pNode node){ stack<int> node_val; while(node){ node_val.push(node->val); node = node->next; } while(!node_val.empty()){ printf("%d\n", node_val.top()); node_val.pop(); } } void List::Recursion_Delete_List(pNode node){ if(node){ Recursion_Delete_List(node->next); delete node; } } void List::Non_Recursion_Delete_List(pNode node){ while(node){ pNode curpNode = node; node = node->next; delete curpNode; } } List::List(){ Head = NULL; Tail = NULL; } List::~List(){ //Recursion_Delete_List(this->Head); Non_Recursion_Delete_List(this->Head); } int main() { List *list = new List; int x; while(scanf("%d", &x) && x >= 0){ list->Non_Recursion_Insert_Node(x); } list->Non_Recursion_Traverse_List(); delete list; return 0; }
相关文章推荐
- jQuery获取复选框checkbox的值的正确方法
- JavaScript
- 转- html lacalStorage
- JQuery 表单校验
- Jquery Ajax的success:funtion(data)的data非son类型
- 用JavaScript代码实现Excel表格的办法
- CSS学习-1
- 我所写的CNN框架 VS caffe
- 动态的创建标记(document.write和innerHTML的使用)
- HTML+CSS D08浮动
- html中a标签中的onclick和href的使用
- ArcGIS API for JavaScript开发笔记(二)GP服务REST调用
- 表格自动换行等前端技能
- javascript中定义事件的三种方式
- 表单标签
- webpack使用笔记
- reverse linked list--javascript
- Web前端开发-11
- JS nodeType返回类型
- jQuery.Callbacks()