链表实现

来源:互联网 发布:sql组合主键 编辑:程序博客网 时间:2024/06/11 10:48

#include <stdio.h>
#include <stdlib.h>

//存储的数据的类型

typedef int elemtype;

//链表结构体
typedef struct Node{
 elemtype num;
 struct Node * next;
}Node0;

//链表指针
typedef Node0* linklist;

//链表初始化

int init(linklist *node)
{

//将头指针指向NULL
 *node=NULL;
 return 0;
}

//计算链表长度
int count_length(linklist node)
{
 linklist temp;
 int length=0;
 for(temp=node;temp!=NULL;temp=temp->next)
  length++;
 return length;
}

//查找对应元素的链表指针
linklist* search(linklist node,elemtype num)
{
 linklist *temp;
 if(node==NULL)
  return NULL;
 for(*temp=node;(*temp)->next!=NULL;(*temp)=(*temp)->next)
  if((*temp)->num==num)
   return temp;
 return NULL;
}

//从链表尾部插入节点
int insert(linklist *node,elemtype num)
{
 linklist temp,temp0;
 temp0=(linklist)malloc(sizeof(Node0));
 temp0->num=num;
 temp0->next=NULL;
 if(*node==NULL)
 {
  *node=temp0;
  return 0;
 }
 for(temp=*node;temp->next!=NULL;temp=temp->next);
  temp->next=temp0;
 return 0;
}

//删除对应节点
int delete(linklist *node,elemtype num)
{
 linklist temp,temp0;
 for(temp=*node;temp!=NULL;temp=temp->next)
 {
  if(temp->num==num)
  {
   temp0->next=temp->next;
   return 0;
  }
  temp0=temp;
 }
 return -1;
}

//遍历并打印整个链表
int show(linklist node)
{
 linklist temp;
 if(node==NULL)
  return -1;
 for(temp=node;temp!=NULL;temp=temp->next)
  printf("%d\n",temp->num);
 return 0;
}
int main()
{
 linklist node;
 init(&node);
 show(node);
 insert(&node,20);
 show(node);
 insert(&node,10);
 show(node);
 insert(&node,30);
 show(node);
 insert(&node,40);
 show(node);
 printf("%d\n",count_length(node));
// printf("%d\n",(*search(node,10))->num);
 delete(&node,10);
 show(node);
 printf("%d\n",(*search(node,30))->num);
 return 0;
}