#include<stdio.h>
#include<stdlib.h>
typedef struct stack{
struct node *base;
struct node *top;
int stacklen;
}stack;
typedef struct node{
int data;
struct node *last;
}node;
void init(stack *p)
{
node *n=(node *)malloc(sizeof(node));
n->last=NULL;
p->base=n;
p->top=n;
p->stacklen=0;
}
void push(stack *p)
{
int num,i,data;
printf("input num\n");
scanf("%d",&num);
for(i=0;i<num;++i)
{
printf("input data\n");
scanf("%d",&data);
node *n=(node *)malloc(sizeof(node));
n->data=data;
n->last=p->top;
p->top=n;
p->stacklen+=1;
}
}
void pop(stack *p)
{
printf("stack length is %d\n",p->stacklen);
while((p->top)->last)
{
printf("%d->",(p->top)->data);
p->top=(p->top)->last;
p->stacklen-=1;
}
printf("end\nstack length is %d\n",p->stacklen);
}
int main()
{
stack p;
init(&p);
push(&p);
pop(&p);
}
结果:
sun@ubuntu:~/project/datastructure$ ./stack
input num
4
input data
1
input data
2
input data
3
input data
4
stack length is 4
4->3->2->1->end
stack length is 0
#include<stdio.h>
#include<stdlib.h>
typedef struct queue{
struct node *head;
struct node *end;
}queue;
typedef struct node{
struct node *next;
int data;
}node;
void init(queue *p)
{
p->head=NULL;
p->end=NULL;
}
void enqueue(queue *p)
{
int data,num;
printf("input num\n");
scanf("%d",&num);
for(int i=0;i<num;++i)
{
printf("input data\n");
scanf("%d",&data);
node *newnode=(node *)malloc(sizeof(node));
newnode->data=data;
newnode->next=NULL;
if(p->head==NULL && p->end==NULL)
{
p->head=newnode;
p->end=newnode;
continue;
}
(p->end)->next=newnode;
p->end=newnode;
}
}
void dequeue(queue *p)
{
while(1)
{
if(p->head==p->end)
{
printf("%d->end\n",(p->head)->data);
p->head=NULL;
p->end=NULL;
break;
}
printf("%d->",(p->head)->data);
p->head=(p->head)->next;
}
}
int main()
{
queue p;
init(&p);
enqueue(&p);
dequeue(&p);
return 0;
}
结果:
sun@ubuntu:~/project/datastructure$ ./queue
input num
7
input data
1
input data
2
input data
3
input data
4
input data
5
input data
6
input data
7
1->2->3->4->5->6->7->end