小弟自我複習的程式碼~
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
typedef struct node NODE;
NODE* push(NODE*,int);
NODE* pop(NODE*);
void print(NODE*);
int main() {
NODE *top = NULL;
int select,val;
printf("==================\n");
printf("<1> push data\n");
printf("<2> pop data\n");
printf("<3> top data\n");
printf("<4> print stack\n");
printf("<5> end\n");
printf("==================\n");
while(1) {
printf("please select: ");
scanf("%d",&select);
switch(select) {
case 1:
printf("please enter a number: ");
scanf("%d",&val);
top = push(top,val);
break;
case 2:
top = pop(top);
break;
case 3:
printf("stack top: %d\n",top->data);
break;
case 4:
printf("stack content: ");
print(top);
printf("\n");
break;
case 5:
return 0;
default:
printf("Please enter a correct number!\n");
}
}
}
NODE *push(NODE *top,int val) {
NODE *newnode = (NODE*)malloc(sizeof(NODE));
newnode->data = val;
newnode->next = top;
return newnode;
}
NODE *pop(NODE *top) {
if(top == NULL) {
printf("stack is empty!\n");
return NULL;
}
printf("Data %d has been deleted!\n",top->data);
NODE *tempnode = top;
top = top->next;
free(tempnode);
return top;
}
void print(NODE*top) {
printf("top ");
while(top != NULL) {
printf("%d ",top->data);
top = top->next;
}
}
2021/12/12 更新:上傳程式碼
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up