你说的对,我改了一下,好了,这段程序是从书上弄下来的,我有个疑问,为什么作者会讲LinkList的类型设置为struct Node*类型,而不直接设置为Node类型呢?
- #include <stdio.h>
- #include <stdlib.h>
- #define OK 1
- #define ERROR 0
- #define TRUE 1
- #define FALSE 0
- typedef int Status;
- typedef int ElemType;
- typedef struct Node{
- ElemType data;
- struct Node *next;
- }Node;
- typedef Node LinkList;
- /*输出所有元素*/
- void PrintfAllElem(LinkList* L){
- Node *p = (Node*)L;
- int i = 0;
- while (p) {
- printf("index is %d,data is %d\n",i,p->data);
- p=p->next;
- ++i;
- }
- }
- /*单链表的读取*/
- Status GetElem(LinkList L,int i,ElemType* e){
- Node* p = L.next;
- int j = 1;
-
- while (j<i && p) {
- p = p->next;
- j++;
- }
-
- if (!p || j > i)
- return ERROR;
- *e = p->data;
- return OK;
- }
- /*插入节点*/
- Status InsertElem(LinkList *list,int i,ElemType e)
- {
- Node *p;
- int j;
-
- p = (Node*)list;
- j = 1;//从第一个位置开始数
-
- while (p && j<i) {
- j++;
- p = p->next;
- }
-
- if (!p || j>i) {
- return ERROR;
- }
-
- Node* new = malloc(sizeof(Node));
-
- new->next = p->next;
- new->data = e;
- p->next = new;
-
- return OK;
- }
- /*删除节点*/
- Status DelElem(LinkList *list,int i){
- Node *p,*q;
- int j;
- p = (Node*)list;
- j = 1;
-
- while (p && j<i) {
- p = p->next;
- j++;
- }
-
- if (!p || j>i) {
- return ERROR;
- }
-
- q = p->next;
- p->next = q->next;
- q->next = NULL;
- free(q);
-
- return OK;
- }
- int main(int argc, const char * argv[]) {
-
- LinkList* l = malloc(sizeof(LinkList));
- Node *n = malloc(sizeof(Node));
- l->next = n;
- l->data = 0;
-
- n->data = 1;
- n->next = NULL;
-
- InsertElem(l, 2, 3);
- InsertElem(l, 3, 4);
- InsertElem(l, 4, 5);
-
- PrintfAllElem(l);
-
- return 0;
- }
复制代码 |