链表

来源:互联网 发布:三国志11项羽数据 编辑:程序博客网 时间:2024/05/09 01:17

链表基于:结构本身不能含有同类型结构,但是可以包含指向同类型结构的指针

单链表:链表尾指针为NULL;

typedef struct a{...;struct a *next; //指向下一个结构体的指针}A;A *head = NULL;//头指针A *prev, *current;while(1){current = (A *)malloc(A);//分配内存!if(!head)head = current; elseprev->next = current;current->next = NULL;//将下一个指针设为NULL,否则尾指针不确定...;prev = current;  //下次分配时,本次结构为前一结构!}//插入节点int i = ...;//插入位置int j = 0;A *pnew;current = head;pnew = (A)malloc(A);while(!current->next && j < i -1){j++;current = current->next;}if(!current && j < i -1){qnew->next = current->next;//把下个结构体指针保存到新结构体中current->next = qnew;//新结构体指针保存到上个结构体中}//删除节点i = ...;//删除位置位置j = 0;current = head;A *temp;temp = head->nextwhile(!current->next && j < i -1){j++;current = current->next;temp = temp->next;}if(!current && j < i -1){current->next = temp->next;//此时链表中已经没有temp指针free(temp);}//清理列表current = head;while(!current){A *temp;temp = current->next; //free的时候current的内存被释放,nextfree(current);      //的内容已经不再确定current = temp;}

循环链表: 尾指针指向头指针

双向链表: 结构体中同时存在前一个结构体指针和下一个结构体指针

typedef struct a{
...;
struct a *prev;
struct a *next; //指向下一个结构体的指针
}A;






0 0