Chinaunix首页 | 论坛 | 博客
  • 博客访问: 330988
  • 博文数量: 73
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1293
  • 用 户 组: 普通用户
  • 注册时间: 2013-03-07 11:17
个人简介

爱运动,爱看书,爱生活!

文章分类

全部博文(73)

文章存档

2014年(7)

2013年(66)

分类: 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);
}

 

 

 

 

 

 

 

 

 

 

 

 

 

阅读(856) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~