好久没有写C的程序了,最近空闲着,所以写了一下C的数据结构。下面简单记录一下c实现链表。
栈的结构操作简单,只能栈顶操作(所以只记录栈顶,之后通过栈顶去找管理的下一个数据),先进后出。直接上码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char DataType;
typedef struct stacknode {
DataType data;//节点数据
struct stacknode *next;
}StackNode,*LinkStack;
//只需要记录它的栈顶
LinkStack top = NULL;
/*方法声明*/
int StackEmpty();
void Push(DataType x);
DataType Pop();
void PrintStack();
int main() {
Push('A');
Push('B');
Push('C');
Push('D');
PrintStack();
printf("pop=%c\n", Pop());
PrintStack();
return 1;
}
int StackEmpty() {
return top == NULL;
}
void Push(DataType x) {
LinkStack newNode;
newNode = (LinkStack) malloc(sizeof(StackNode));
newNode->data = x;
newNode->next = top;
top = newNode;
}
DataType Pop() {
LinkStack t;
DataType temp;
if (!StackEmpty()) {
t = top;
top = top->next;
temp = t->data;
free(t);
return temp;
} else {
printf("empty stack!");
exit(0);
}
}
void PrintStack() {
LinkStack temp = NULL;
temp = top;
if (!StackEmpty()) {
while (temp != NULL) {
printf("[%c]", temp->data);
temp = temp->next;
}
printf("\n");
}
}
gcc运行后的结果:
simple总结一下:
* c的程序比java更加精巧而且控制感强;
* c的程序没有什么软件设计的感觉的,存函数式的
* 写栈时确定是链式存储还是线序栈。
应用:10进制转2,3,4—n(n,<10)进制,当除到为零为止,更改一下代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int DataType;
typedef struct stacknode {
DataType data;//节点数据
struct stacknode *next;
} StackNode, *LinkStack;
/*方法声明*/
int StackEmpty(LinkStack top);
void Push(DataType x);
DataType Pop();
DataType GetTop();
void PrintStack();
void convert(int number, int dex);
LinkStack top;
int main() {
convert(100, 2);
return 1;
}
void convert(int number, int dex) {
if (dex > 10) {
printf("不支持转化范围!");
} else {
printf("convert %d to %d=", number, dex);
while (number) {
Push(number % dex);
number = number / dex;
}
while (!StackEmpty(top)) {
printf("%d", Pop());
}
printf("\n");
}
}
int StackEmpty(LinkStack top) {
return top == NULL;
}
void Push(DataType x) {
LinkStack newNode;
newNode = (LinkStack) malloc(sizeof(StackNode));
newNode->data = x;
newNode->next = top;
top = newNode;
}
DataType Pop() {
DataType x;
LinkStack t = NULL;
t = top;
if (!StackEmpty(top)) {
t = top;
top = top->next;
x = t->data;
free(t);
return x;
} else {
printf("empty stack!");
exit(0);
}
}
DataType GetTop() {
if (StackEmpty(top)) {
printf("stack empty");
exit(0);
} else {
return top->data;
}
}
void PrintStack() {
LinkStack temp;
temp = top;
if (!StackEmpty(temp)) {
while (temp != NULL) {
printf("[%d] ", temp->data);
temp = temp->next;
}
printf("\n");
}
}
本文参考数严蔚敏的据结构书籍。