#include <stdlib.h>
#include <stdio.h>
#include <time.h>
struct Node{
int value;
struct Node *next;
};
typedef struct Node LStackNode;
typedef struct Node *LinkedStack;
LinkedStack LinkedStackInit(LinkedStack s){
s=NULL;
return s;
}
LinkedStack LinkedPush(LinkedStack s,int x){
LStackNode *n;
n=(LStackNode *)malloc(sizeof(LStackNode));
if(!n) exit(-1);
n->value=x;
if(s==NULL){
s=n;
}else{
n->next=s;
s=n;
}
return s;
}
LinkedStack LinkedPop(LinkedStack s){
if(s==NULL) exit(0);
int r=s->value;
printf("%d \t",r);
LStackNode *t;
t=s;
s=s->next;
free(t);
return s;
}
void printfLStack(LinkedStack t){
int i;
i=0;
while(t!=NULL){
t=LinkedPop(t);
}
}
void main(){
int n;
int m;
printf("please input the number: \n");
scanf("%d",&n);
srand(time(NULL));
LinkedStack Seven,Sodd;
Seven=LinkedStackInit(Seven);
Sodd=LinkedStackInit(Sodd);
int i=0;
for(i;i<n;i++){
m=rand()%100;
printf("%d \t",m);
if(m%2==0){
Seven=LinkedPush(Seven,m);
}else{
Sodd=LinkedPush(Sodd,m);
}
}
printf("\n Seven num:\n");
printfLStack(Seven);
printf("\n Sodd num:\n");
printfLStack(Sodd);
printf("\n");
}
指针实现篇
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
struct Node{
int value;
struct Node *next;
};
typedef struct Node LStackNode;
typedef struct Node *LinkedStack;
LinkedStackInit(LinkedStack *s){
*s=NULL;
}
void LinkedPush(LinkedStack *s,int x){
LStackNode *n;
n=(LStackNode *)malloc(sizeof(LStackNode));
if(!n) exit(-1);
n->value=x;
if(*s==NULL){
*s=n;
}else{
n->next=*s;
*s=n;
}
}
void LinkedPop(LinkedStack *s){
if(*s==NULL) exit(0);
int r=(**s).value;
printf("%d \t",r);
LStackNode *t;
t=*s;
*s=(**s).next;
free(t);
}
void printfLStack(LinkedStack * t){
int i;
while(*t!=NULL){
LinkedPop(t);
}
}
void main(){
int n;
int m;
printf("please input the number: \n");
scanf("%d",&n);
srand(time(NULL));
LinkedStack Seven,Sodd;
LinkedStackInit(&Seven);
LinkedStackInit(&Sodd);
int i=0;
for(i;i<n;i++){
m=rand()%100;
printf("%d \t",m);
if(m%2==0){
LinkedPush(&Seven,m);
}else{
LinkedPush(&Sodd,m);
}
}
printf("\n Seven num:\n");
printfLStack(&Seven);
printf("\n Sodd num:\n");
printfLStack(&Sodd);
printf("\n");
}
本文涉及的 结构体方面的知识可以参考