将数组a[11]={1, 3, 6, 10, 15, 16, 17, 18, 19, 20}; 通过栈和队列实现元素逆置的算法,
入栈->出栈->入队->出队
#include"stdio.h"
#include"stdlib.h"
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}linkqene;
linkqene *push(linkqene *rear,datatype x)
{
linkqene *s;
s=(linkqene *)malloc(sizeof(linkqene));
s->data=x;
s->next=NULL;
rear->next=s;
rear=s;
return rear;
}
int pop(linkqene *front,linkqene *rear)
{
linkqene *p;
datatype x;
if (rear==front) { printf("队空\n");exit(0);}
p=front->next;
x=p->data;
front->next=p->next;
if (p->next==NULL) rear=front;
free( p);
return x;
}
typedef int datatype;
typedef struct node1{
datatype data;
struct node1 *next;
}linkstack;
linkstack *top;
int i=0,j=0;
linkstack *push1(linkstack *top,datatype x)
{
linkstack *s;
s=(linkstack *)malloc(sizeof(linkstack));
s->data=x;
s->next=top;
top=s;
return top;
}
void pop2(linkstack *top)
{
datatype x;
linkstack* p;
while(top)
{
p=top;
x=p->data;
printf("%d ",x);
top=top->next;
free(p);
}
}
main()
{
int x,x1=0,i;
linkqene *rear,*front;
front=(linkqene *)malloc(sizeof(linkqene));
front->next=NULL;
rear=front;
int a[11]={1, 3, 6, 10, 15, 16, 17, 18, 19, 20};
for(i=0;i<10;i++)
{
int x=a[i];
rear=push(rear,x);
}
linkstack *top=NULL;
datatype x3;
puts("入队成功");
for(i=0;i<10;i++)
{
x1=pop(front,rear);
top=push1(top,x1);
}
puts("入栈成功");
puts("倒序输出为");
pop2(top);
}