赞
踩
1、单链表构成的循环链表
最后一个结点本来指向NULL,改为指向头结点或者第一个结点。
实现方法,将原来指向NULL的地方改成指向ls->head,或者ls->head->next。
While()循环的条件改为!= ls->head或者ls->head->next。
#include "Linklist.h" #include <stdlib.h> #include <stdio.h> List *Creat() { List *ls = (List *)malloc(sizeof(List)/sizeof(char)); if(NULL == ls) return NULL; ls->head = (Node *)malloc(sizeof(Node)/sizeof(char)); if(NULL == ls->head) { free(ls); return NULL; } ls->head->next = NULL; ls->head->pre = NULL; return ls; } //头插 BOOL inster_head(List *ls,Data data) { if(NULL == ls) return ERROR; Node *pa = (Node *)malloc(sizeof(Node)/sizeof(char)); if(NULL == pa) return ERROR; pa->data = data; pa->next = ls->head->next; pa->pre = ls->head; ls->head->next = pa; if(pa->next != NULL) pa->next->pre = pa; return TRUE; } //尾插 BOOL inster_last(List *ls,Data data) { if(NULL == ls) return ERROR; Node *pa = (Node *)malloc(sizeof(Node)/sizeof(char)); if(NULL == pa) return ERROR; pa->data = data; pa->next = NULL; Node *tmp = ls->head; while(tmp->next) { tmp = tmp->next; } tmp->next = pa; pa->pre = tmp; return TRUE; } //链表按位置插 BOOL inster_pos(List *ls,int index,Data data) { if(NULL == ls || index < 1) return ERROR; Node *pa = (Node *)malloc(sizeof(Node)/sizeof(char)); if(NULL == pa) return ERROR; Node *tmp = ls->head; int i; for(i = 0; i < index-1; i++) { tmp = tmp->next; if(tmp == NULL) { printf("链表越界,长度=%d\n",index); return ERROR; } } pa->data = data; //要插入的数据 pa->next = tmp->next; pa->pre = tmp; tmp->next = pa; if(pa->next != NULL) pa->next->pre = pa; return TRUE; } //删除数据(按位置) BOOL delete_index(List *ls,int index) { if(NULL == ls) return; Node *tmp = ls->head; int i; for(i = 0; i < index-1; i++) { tmp = tmp->next; if(NULL =&
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。