一个简单的双向循环链表的实现的代码: typedef struct Data{ int index; char name[256];}Data_t;typedef struct DList{ void *data; struct DList *prior, *next;}DList;void InitList(DList **head) //初始化链表(方法一),表头为空{ *head = (DList *)malloc(LEN); if(head) (*head)->next = (*head)->prior = *head; else exit(0);}DList* InitNewList(DList *head) //初始化链表(方法二),表头为空{ head = (DList *)malloc(LEN); if(head) head->next = head->prior = head; else exit(0); return head;}int ListLength(DList *head) //获得链表的长度(不计表头){ DList *p; int i; if(!head) { printf("empty list!"); return 0; } p = head->next; i = 0; while(p != head) { i++; p = p->next; } return i;}DList *GetP(DList *head, int i) //获得指定的链表节点{ DList *p; int j; if(i<0 || i>ListLength(head)) return NULL; p=head; for(j=0; j<i; j++) p = p->next; return p;}void Insert(DList *head, int i, void *t) //插入一个节点{ int j=0; DList *p, *s; if(i<1 || i>ListLength(head)+1) { printf("Insert error/n"); exit(0); } s = GetP(head, i-1); if(!s) { printf("error/n"); exit(0); } p=(DList *)malloc(LEN); if(!p) { printf("error/n"); exit(0); } p->data = t; p->prior = s; p->next = s->next; s->next->prior = p; s->next = p; }void Delete(DList *head, int i) //删除一个节点{ DList *p, *s; if(i<1 || i>ListLength(head)+1) { printf("Insert error/n"); exit(0); } s = GetP(head, i-1); p = GetP(head, i); if((!s)&&(!p)) { printf("error/n"); exit(0); }s->next = p->next;p->next->prior = s; free(p); p = NULL;}void print1(DList *head) //顺序打印所有节点{ DList *p = head->next; while(p != head) { Data_t *d = (Data_t*)p->data; printf("index = %d,name = %s/n",d->index,d->name); p = p->next; } printf("/n");}void print2(DList *head) //逆序打印所有节点{ DList *p = head->prior; while(p != head) { Data_t *d = (Data_t*)p->data; printf("index = %d,name = %s/n",d->index,d->name); p = p->prior; } printf("/n");}int main(void){ DList *head; int i,len; char ch = 'A'; char temp[256]; Data_t data[5]; for(i = 0; i < 5; i++) { data[i].index = i+1; sprintf(temp,"%c",ch+1+i); strcpy(data[i].name,temp); } //InitList(&head); head = InitNewList(head); for(i=0; i<5; i++) Insert(head, i+1, &data[i]); print1(head); print2(head); return 0;}typedef struct Data{ 你的当前访问异常,请进行认证后继续阅读剩余内容。 提交