LinList.h //单链表,线性表的链式表示 #include "stdio.h" #include "math.h" typedef struct Node { DataType data; struct Node *next; } SLNode; void ListInitiate(SLNode **head) { if (( *head = (SLNode *)malloc(sizeof(SLNode))) == NULL ) exit(1); (*head)->next = NULL; } int ListLength(SLNode * head) { SLNode *p = head; int size = 0; //默认头节点没有数据 while (p->next != NULL) { p = p->next; size++; } return size; } //在带头节点的单链表head的第i(0<=i<=size)个结点前插入 int ListInsert(SLNode * head, int i, DataType x) { SLNode *p, *q; int j; p = head; j = -1; //其实就是i-1-(-1)=i次,把p指针移到第i-1个结点上,因为结点从0开始 while(p->next != NULL && j < i-1) { p = p->next; j++; } if ( j != i-1) { printf("insert error !/n"); return 0; } if ((q = (SLNode *)malloc(sizeof(SLNode))) == NULL) exit(1); q->data = x; q->next = p->next; p->next = q; return 1; } int ListDelete(SLNode * head, int i, DataType *x) { SLNode *p, *s; int j = -1; p = head; //其实就是i-1-(-1)=i次,把p指针移到第i-1个结点上,因为结点从0开始 while(p->next != NULL && j < i-1) { p = p->next; j++; } if ( j != i-1) { printf("delete error !/n"); return 0; } s = p->next; *x = s->data; p->next = p->next->next; free(s); return 1; } int ListGet(SLNode * head, int i, DataType *x) { SLNode *p, *s; int j = -1; p = head; //其实就是i-(-1)=i+1次,把p指针移到第i个结点上,因为结点从0开始 while(p->next != NULL && j < i) { p = p->next; j++; } if ( j != i) { printf("getData error !/n"); return 0; } *x = p->data; return 1; } //释放动态申请的内存空间 void Destroy(SLNode * *head) { SLNode *p, *p1; p = *head; while(p != NULL) { p1 = p; p = p->next; free(p1); } * head = NULL; } LinListApp1.cpp #include "stdio.h" #include "stdlib.h" //exit() #include "malloc.h" //malloc() typedef int DataType; #include "LinList.h" void main() { SLNode * myhead; int i, x; ListInitiate(&myhead); for (i = 0; i < 10; i++) { ListInsert(myhead, i, i+1); } ListDelete(myhead, 4, &x); for (i = 0; i < ListLength(myhead); i++) { ListGet(myhead, i, &x); printf("%d ", x); } Destroy(&myhead); }