#include<stdio.h>
#include<iostream>
using namespace std;
struct stack{ // 定义栈结构,用于实现链表反向输出
int data[100];
int top;
};
struct node{
int data;
struct node *next;
};
struct node *createList(int n){ //创建n个结点链表
struct node *head;
head=(struct node *)malloc(sizeof(struct node));
struct node *p=head;
struct node *q;
for(int i=1;i<n;i++){
q=(struct node *)malloc(sizeof(struct node));
cin>>p->data;
p->next=q;
p=q;
}
cin>>p->data;
p->next=NULL;
return head;
}
void printlistnode(struct node* head){ // 正想打印链表
struct node* p=head;
while(p != NULL){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void reverseprintlistnode(struct node *head){ //反向打印链表 利用栈结构实现
struct node* p=head;
struct stack s;
s.top=0;
while(p != NULL){
s.data[s.top] = p->data;
++s.top;
p=p->next;
}
while(s.top>0){
--s.top;
cout<<s.data[s.top]<<" ";
}
cout<<endl;
}
//递归实现反向打印链表结点
void reverseprintlistnode_acle(struct node *head){
if(head != NULL){
if (head->next != NULL)
reverseprintlistnode_acle(head->next);
cout<<head->data<<" ";
}
}
int main(){
int n;
struct node* head;
cin>>n;
head=createList(n);
printlistnode(head);
reverseprintlistnode(head);
reverseprintlistnode_acle(head);
cout<<endl;
free(head);
return 0;
}
链表操作
最新推荐文章于 2021-09-23 21:10:08 发布