逆向输出链表

来源:互联网 发布:天津知豆电动汽车销售 编辑:程序博客网 时间:2024/05/05 14:17
在不改变链表结构的前提下,使用一个后进先出的数据结构(栈)存储正向遍历链表的结果,根据后进先出的特点:最后一个进入的数据最先被弹出,可以逆向打印出链表。我们也可以根据递归来逆向输出链表。
#include<iostream>#include<stack>using namespace std;//链表的节点类型struct Node{int data;Node *next;};//在链表末尾插入一个元素void addTailNode(Node *&head,int val){Node *p = new Node;//创建一个节点p->data = val;p->next = NULL;if(head == NULL)//判断链表是否为空{head = p;}else{Node *tmp = head;//tmp指向链表的末尾while(tmp->next != NULL){tmp = tmp->next;}tmp->next = p;}}//正向输出链表void show(Node *head){while(head != NULL){cout<<head->data<<endl;head = head->next;}}//使用递归的方法逆向输出链表void reverseShow01(Node *head){if(head != NULL){reverseShow01(head->next);cout<<head->data<<" ";}}//使用栈作为数据结构逆向输出链表void reverseShow02(Node *head){stack<int> s;//创建s,栈中存储的是节点中值类型while(head != NULL)//链表不为空入栈{s.push(head->data);head = head->next;}while(!s.empty())//栈不为空,输出栈顶元素,并输出{cout<<s.top()<<" ";s.pop();}cout<<endl;}int main(void){Node *head = NULL;//创建一个空的链表for(int i = 0; i < 10; ++i)//在链表中插入10个数{addTailNode(head,i);}reverseShow01(head);//逆向输出链表cout<<endl;reverseShow02(head);//逆向输出链表system("pause");return 0;}
输出结果:
9 8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0
0 0
原创粉丝点击