借用栈实现单链表逆向倒序输出

来源:互联网 发布:洛奇英雄传mac 编辑:程序博客网 时间:2024/06/11 11:14
// StackTest.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;


typedef struct LinkNode {
int value;
LinkNode *next;

};
/*
创建链表,头结点存放结点数目。
*/
LinkNode *CreateList() {
LinkNode *head;//指向头结点指针
LinkNode *p, *pre;
int a;
head = (LinkNode *)malloc(sizeof(LinkNode));//为头节点分配内存空间
//初试为0
head->value = 0;
head->next = NULL;//将头结点的指针域清空
// pre = head;//先将头结点首地址赋给中间变量pre
cout << "LinkNode is creating!" << endl;
return head;
}
//在尾结点添加数据
void Insert(LinkNode *linkNode,int key) {
LinkNode *p,*q;
q = linkNode;
q->value++; //结点数目加1
cout << "Data is inserting" << endl;
p = (LinkNode*)malloc(sizeof(LinkNode));
p->value = key;
p->next = NULL;
if (q == NULL)
{
q = p;
q->next = NULL;
exit(0);
}
while (q->next != NULL) 
{
q = q->next;
}


q->next = p;
// q->next->next = NULL;
}
//顺序输出
void Output(LinkNode *linkNode) {
LinkNode *head;
head = linkNode;
while (head != NULL) {
cout << head->value << " ";
head = head->next;
}
cout << endl;
}
//逆向输出
stack<int> reOutput(LinkNode *linkNode) {
LinkNode *head;
stack<int> s;
head = linkNode;
while (head != NULL) {
s.push(head->value);
head = head->next;
}
return s;
}


int main()
{
LinkNode *linkNode;
linkNode = NULL;
linkNode = CreateList();
//插入数据
Insert(linkNode,1);
Insert(linkNode, 2);
Insert(linkNode, 3);
//手动输入
for (int i = 0; i < 3; i++) {
int t;
cin >> t;
Insert(linkNode, t);
}
Output(linkNode);
 
stack<int> s;
s = reOutput(linkNode);
while (!s.empty()) {
cout << s.top() << endl;
s.pop();
}

system("pause");
    return 0;


}

原创粉丝点击