基本链表的创建,结点插入、删除

来源:互联网 发布:c语言计算器三角函数 编辑:程序博客网 时间:2024/06/11 13:57

#include <stdio.h>
#include <stdlib.h>
typedef struct llist{
 int data;
 struct llist *next;
}node,*link;
//输出链表
void printlist(link head)
{
 link ptr;
 ptr=head->next;
 while(ptr!=NULL)
 {
  printf("%d ",ptr->data);
  ptr=ptr->next;
 }
 printf("\n");
}
//创建链表
link createlist(int *array,int n)
{
 link head;
 link ptr,ptr1;
 int i;
 head=(link)malloc(sizeof(node));
 if(!head)
 {
  printf("out of memory\n");
  exit(1);
 }
 ptr=head;
 printf("请输入你想输出的链表!\n");
 for(i=0;i<n;i++)
 {
  scanf("%d",&array[i]);
  ptr1=(link)malloc(sizeof(node));
  if(!ptr1)
  {
   printf("out of memory!\n");
   exit(1);
  }
  ptr1->data=array[i];
  ptr1->next=NULL;
  ptr->next=ptr1;
  ptr=ptr1;
 }
 return head;
}
//寻找结点
link findnode(link head,int value)
{
 link ptr;
 ptr=head->next;
 while(ptr!=NULL)
 {
  if(ptr->data==value)
   return ptr;
  else
   ptr=ptr->next;
 }
 return NULL;
}
//插入结点
link insertnode(link head,int insertvalue)
{
 link newnode,getnode;
 newnode=(link)malloc(sizeof(node));
 if(!newnode)
 {
  printf("out of memory!\n");
  exit(1);
 }
 newnode->data=insertvalue;
 newnode->next=NULL;
 getnode=findnode(head,insertvalue);
 if(!getnode)//如果没有找到结点,就插入到第一个结点之前
 {
  newnode->next=head->next;
  head->next=newnode;
 }
 else//找到指定结点,就插入到指定结点后面
 {
  newnode->next=getnode->next;
  getnode->next=newnode;
 }
 return head;
}
//删除结点
link deletenode(link head,link ptr)
{
 link previous;
 previous=head;
 while(previous->next!=ptr)
 {
  previous=previous->next;
 }
 if(ptr->next==NULL)//删除尾结点
  previous->next=NULL;
 else
  previous->next=ptr->next;
 return head;

//主函数
void main()
{
 int array[5];
 int insertvalue,deletevalue;
 link ptr;
 link head;
 head=createlist(array,5);//创建链表
 printlist(head);//输出创建的链表
 printf("请输入你要插入的结点!\n");
 scanf("%d",&insertvalue);
 insertnode(head,insertvalue);//插入结点
 printlist(head);//输出插入结点后的链表
 printf("请输入你要删除的结点\n");
 scanf("%d",&deletevalue);
 ptr=findnode(head,deletevalue);
 deletenode(head,ptr);
 printlist(head);//输出删除结点后的链表
}

   

原创粉丝点击