您的位置:首页 > Web前端

剑指offer 从尾到头打印链表

2016-03-08 20:54 387 查看
题目描述:

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

思路:

很多方法,最有用的就是真的实现一个链表然后进行操作。

一开始我的做法是每次插入先从头结点遍历到尾结点,然后进行插入操作,但是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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: