爱运动,爱看书,爱生活!
分类: C/C++
2013-05-26 19:18:02
#include
#include
#include
typedef int data_type;
//节点
typedef struct node{
data_type data;
struct node *next;
}node;
//初始化
void list_initiate(node **head)
{
*head=(node*)malloc(sizeof(node));
(*head)->next=NULL;
}
//求当前数据元素个数
int list_length(node *head)
{
node *p=head;
int size=0;
while(p->next!=NULL){
p=p->next;
size++;
}
return size;
}
//插入
int list_insert(node *head,int i,data_type x)
{
node *p,*q;
int j;
p=head;
j=-1;
while(p->next!=NULL && j
p=p->next;
j++;
}
if(j!=i-1){
printf("插入错误。\n");
return 0;
}
q=(node*)malloc(sizeof(node)) ;
q->data=x;
q->next=p->next;
p->next=q;
return 1;
}
//删除
int list_delete(node *head,int i,data_type *x)
{
node *p,*s;
int j;
p=head;
j=-1;
while(p->next!=NULL && p->next->next!=NULL && j
{
p=p->next;
j++;
}
if(j!=i-1){
printf(" delete error.\n");
return 0;
}
s=p->next;
*x=s->data;
p->next=p->next->next;
free(s);
return 1;
}
//取数据元素
int list_get(node *head,int i,data_type *x)
{
node *p;
int j;
p=head;
j=-1;
while(p->next!=NULL && j
p=p->next;
j++;
}
if(j!=i){
printf("get error.\n");
return 0;
}
*x=p->data;
return 1;
}
//释放整个单链表
void destory(node **head)
{
node *p,*p1;
p=*head ;
while(p!=NULL){
p1=p;
p=p->next;
free(p1);
}
*head=NULL;
}
int main()
{
node *head;
int i,x;
list_initiate(&head);
for(i=0;i<10;i++){
list_insert(head,i,i+1);
}
for(i=0;i
list_get(head,i,&x);
printf("%d ",x);
}
printf("\n");
list_delete(head,4,&x);
for(i=0;i
list_get(head,i,&x);
printf("%d ",x);
}
printf("\n");
destory(&head);
}