原文:C语言双向链表
今天写了点双向链表的各种操作,写插入的时候费了点时间,不过,现在看来还是值得耗费那点时间去写的,这种小东西应该能信手拈来才行啊。
/*双向链表*/
#include <stdio.h>
#include <string.h> /*strcmp(const char *,const char *) return 0 is equal*/ typedef struct dulnode
{
char name[];
struct dulnode *prior,*next;
}stud;
/*创建,返回链表头指针,参数n-节点个数*/
stud * create(n);
/*查找,返回节点地址,参数h-链表头指针,name为查询条件*/
stud * search(stud *h,char *name);
/*删除*/
void del(stud *p);
/*显示,参数-h,链表头节点,num-显示节点个数*/
void show(stud *h,int num);
/*求链表长度*/
int length(stud *head);
/*插入节点,参数head-链表头节点,name-节点,n-节点位置*/
stud *insert(stud *head,char *name,int n);
int main()
{
stud *head,*re,*in;
head = create();
show(head,);
re = search(head,"Accipiter");
show(re,);
del(re);
re = head->next;
show(re ,);
in = insert(re , "cnblogs",);
show(in,);
return ;
}
void show(stud *head,int num)
{
stud *sp;
int cnt = ;
if(NULL == head)
{
printf("It's NULL!\n");
return;
}
if(num>length(head))
{
printf("It's Full\n");
return ;
}
if(strcmp(head->name,"") == )
{
sp = head->next;
}
else
{
sp = head;
}
while(sp)
{
printf("name %d:%s\n",cnt,sp->name);
if(cnt == num)
{
sp = NULL;
}else
{
sp = sp->next;
cnt++;
}
}
} stud * create(n)
{
stud *p,*h,*s;/*p-前指针,h-头指针,s-后指针*/
int i;
/*构建头指针*/
h = (stud *)malloc(sizeof(stud));
if(h == NULL)
{
return NULL;
}
h->name[] = '\0';
h->prior = NULL;
h->next = NULL;
/*插入节点*/
p = h;
for(i=;i<n;i++)
{
s = (stud *)malloc(sizeof(stud));
if(NULL == s)
{
printf("node malloc error!\n");
break;
}
p->next = s;
printf("%d's name:\n",i+);
gets(s->name);
s->prior = p;
s->next = NULL;/*末尾插入*/
p = s;
}
p->next = NULL;
return (h);
} stud * search(stud *head , char *name)
{
stud *p,*re=NULL;
p=head->next;
while(p)
{
if(strcmp(p->name,name) == )
{
re = p;
p = NULL;
}
else
{
p = p->next;
}
}
if(re == NULL)
{
printf("Can't Find!\n");
}
return (re);
} void del(stud *p)
{
if(p == NULL|| (strcmp(p->name,"")==))
{
printf("is Null or head!\n");
return;
}
else
{
p->next->prior = p->prior;
p->prior->next = p->next;
free(p);
}
} int length(stud *head)
{
int len=;
stud *sp;
if(head != NULL)
{
len = ;
sp = head->next;
while(sp)
{
sp = sp->next;
len++;
}
}
return len;
} stud *insert(stud *head , char *name , int n)
{
stud *p,*nhead;
int cnt=;
if(strcmp(head->name,"") != )
{
cnt=;
}
nhead = head;
if(n>length(head)||n<)
{
printf("It's Full or Error!\n");
return NULL;
}
/*插入节点*/
while(cnt<n)
{
head = head->next;
cnt++;
}
p = (stud *)malloc(sizeof(stud));
if(p != NULL)
{
strcpy(p->name,name);
p->next = head->next;
p->prior = head; if(head->next)/*双向链表操作这里很重要*/
head->next->prior=p;
head->next=p;
} return nhead;
}