栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言之单链表的插入、删除与查找

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言之单链表的插入、删除与查找

单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。要实现对单链表中节点的插入、删除与查找的功能,就要先进行的单链表的初始化、创建和遍历,进而实现各功能,以下是对单链表节点的插入、删除、查找功能的具体实现:

#include
#include
#include

typedef int ElemType;

 
typedef struct Node{
 ElemType data;
 struct Node *next;
}Node; 


 
void initList(Node **pNode){
 *pNode=NULL;
}

 
Node *create(Node *pHead){
 Node *p1;
 Node *p2;
 p1=p2=(Node *)malloc(sizeof(Node));     //申请内存空间 
 memset(p1,0,sizeof(Node));//存入数据域清空 
 scanf("%d",&p1->data);
 p1->next=NULL;   
 while(p1->data>0){  //输入负数结束   
  if(pHead==NULL)
   pHead=p1;
  else
   p2->next=p1;
  p2=p1;
  p1=(Node *)malloc(sizeof(Node));
  memset(p1,0,sizeof(Node));
  scanf("%d",&p1->data);
  p1->next=NULL;
 }
 return pHead;
}

 
void printList(Node *pHead){
 if(NULL==pHead)
  printf("链表为空n");
 else{
  while(pHead!=NULL){
   printf("%d ",pHead->data);
   pHead=pHead->next;
  }
 } 
 printf("n");
} 

 
void insert_data(Node **pNode,int i){
 Node *temp;
 Node *target;
 Node *p;
 int item;
 int j=1;
 printf("输入要插入的节点值:");
 scanf("%d",&item);
 target=*pNode;      
 for(;jnext,++j);  //不断移动target位置,到要插入结点位置, 
 temp=(Node *)malloc(sizeof(Node));   //申请内存空间 
 temp->data=item;//存入要存入的数据位置 
 p=target->next; 
 target->next=temp;
 temp->next=p; 
} 

 
void delete_data(Node **pNode,int i){
 Node *target;
 Node *temp;
 int j=1;
 target=*pNode;
 for(;jnext,++j);
 temp=target->next;
 target->next=temp->next;
 free(temp);
}

int search_data(Node *pNode,int elem){
 Node *target;
 int i=1;
 for(target=pNode;target->data!=elem && target->next!=NULL;++i,target=target->next);
 if(target->next==NULL)
  return 0;
 else 
  return i;
 
} 
int main(){
 int i;
 Node *pHead=NULL;
 initList(&pHead);
 pHead=create(pHead);
 printList(pHead);
 printf("输入插入节点位置n");
 scanf("%d",&i);
 insert_data(&pHead,i);
 printList(pHead);
 printf("输入删除节点位置n");
 scanf("%d",&i);
 delete_data(&pHead,i);
 printList(pHead);
 printf("输入查找节点n");
 scanf("%d",&i);
 printf("节点所在位置:%d",search_data(pHead,i));
 return 0;
}

通过以上各功能的实现,希望对大家单链表的学习有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/65056.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号