今天我写了一个双重指针的链表!!!
也就是指针的指针,用指针存储结构体地址,用双重指针储存地址的地址。
这里代码添加了大量注释
代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef enum Status{
success,fail,fatal,range_error
} Status;
typedef struct node{ //一个节点的
int elem;
struct node* next;
} Node, * Ptr;
typedef Ptr* sqlistptr; // int a=10,int *p=&a,int **q=&p
//相当于struct node **sqlistptr//*q=p,**q=a
Status List_Init(sqlistptr L){ //初始化
Status s = fatal;
(*L) = (Ptr)malloc(sizeof(Node));
if(*L){
(*L)->next = NULL;
s = success;
}
return s;
}
Status List_HICreate(sqlistptr L,int date[],int len){
Status s;
Ptr new; //创建单链表(头插法)
int i;
s = List_Init(L);
if (s == success){
for(i=len-1;i>=0;i--){
new = (Ptr)malloc(sizeof(Node));
if(new){
new->elem = date[i];
new->next = (*L)->next;
(*L)->next = new;
}
else {
s=fail; break;
}
}
}
}
Status List_RICreate(sqlistptr L,int date[],int len ){ //尾插法
Status s;
Ptr new,curr;
int i;
s = List_Init(L);
curr = *L;
if (s == success){
for(i=len-1;i>=0;i--){
new = (Ptr)malloc(sizeof(Node));
if(new){
new->elem = date[i];
new->next = curr->next;
curr->next = new;
curr = new; //指针后移
}
else {
s=fail;
break;
}
}
}
}
Status List_Retrieve(sqlistptr L,int pos,int *elem)//按位置查找
{
Status s=range_error;
Ptr p = (*L)->next;
int i=1;
while(i < pos && p){
i++;
p=p->next;
}
if(i == pos){
*elem = p->elem;
s = success;
}
return s;
}
Status List_Retrival(sqlistptr L,int pos,sqlistptr elem)//插入删除的查找
{
Status s = range_error;
int i=0,j;
Ptr p = (*L);
while(p && i<pos){
i++;
p = p->next;
}
if(p && i==pos){
*elem = p;
s = success;
}
return s;
}
Status List_Insert(sqlistptr L,int pos,int elem)
{
Status st;
Ptr p,s;
st=List_Retrival(L,pos-1,&p);
if (st==success){
s=(Ptr)malloc(sizeof(Node));
if(s){
s->elem=elem;
s->next=p->next;
p->next=s;
st=success;
}
else st = fatal;
}
else st = range_error;
}
Status List_Delate(sqlistptr L,int pos){
Status k=fail;
Ptr s,p;
k= List_Retrival(L,pos-1,&p);
if(k == success){
s = p->next;
p->next = s->next;
free(s);
s = NULL;
k = success;
}
return k;
}
void print(sqlistptr L){
Ptr p=(*L);
while(p->next!=NULL){
p = p->next; //指针后移
printf("%d",p->elem);
}
}
int main()
{
Ptr Q;
int elem[100],n,i,j,pos;
printf("输入数据元素个数: ");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&elem[i]);
}
List_Init(&Q);
List_HICreate(&Q,elem,n);//头插
//List_RICreate(&Q,elem,n);//尾插
//List_Retrieve(sqlistptr L,int pos,int *elem)//按位置查找
scanf("%d %d",&pos,&j);
List_Insert(&Q,pos,j);
print(&Q);
return 0;
}