数据结构之链表(Studing< Play with DataStruct>)
线性表链式存储_LinkList
#include <stdio.h> #include<stdlib.h> #include <time.h> #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 typedef int Status;/* Status是函数的类型,其值是函数结果状态代码,如OK等 */ typedef int ElemType;/* ElemType类型根据实际情况而定,这里假设为int */ typedef struct Node{ int data; struct Node *next; }Node; typedef Node *LinkList; //单链表的创建 void CreateListHead(LinkList *L,int n){//这里的LinkList*相当于二级指针 LinkList p;//结构体指针 int i; srand(time(0)); *L = (LinkList)malloc(sizeof(Node)); (*L)->next = NULL; for(i=0;i<n;i++) { p = (LinkList)malloc(sizeof(Node)); p->data = rand()%100+1; p->next = (*L)->next; (*L)->next = p; } } //读取 Status GetElem(LinkList L,int i,ElemType *e){ int j; LinkList p; p = L->next; j = 1; while(p&&j<i){ p = p ->next; ++j; } if(!p||j>i) return ERROR; *e = p->data; return OK; } //插入 Status ListInsert(LinkList *L,int i,ElemType e){ int j; LinkList p,s; p = *L; j = 1; while(p&&j<i){ p = p->next; ++j; } if(!p||j>i){ return ERROR; } s = (LinkList)malloc(sizeof(Node)); s->data = e; s->next = p->next; p->next = s; return OK; } //删除 Status ListDelete(LinkList *L,int i,ElemType *e){ int j; LinkList p,q; p = *L; j = 1; while(p->next &&j<i) { p = p->next; ++j; } if(!(p->next)||j>i) return ERROR; q = p->next; p ->next = q ->next; *e = q ->data; free(q); return OK; } Status ClearList(LinkList*L){ LinkList p,q; p = (*L)->next; while(p){ q = p->next; free(p); p = q; } (*L)->next = NULL; return OK; } int main(){ int *p = (int*)malloc(sizeof(int)); LinkList* head=(LinkList*)malloc(sizeof(Node));//给头指针分配内存空间 CreateListHead(head,10);//创建链表 ListInsert(head,4,0);//插入 GetElem((*head),4,p);//取出链表对应位置的元素 printf("%d\n",*p); return 0; }
大多数想法要么平庸,要么更糟糕,这很大程度上因为绝妙的想法难得一见,而且他们还要在我们身边这个充斥了各种恶俗的所谓常识的环境中孕育生长。