国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C > 正文

C語言之單鏈表的插入、刪除與查找

2020-01-26 15:01:27
字體:
來源:轉載
供稿:網友

單鏈表是一種鏈式存取的數據結構,用一組地址任意的存儲單元存放線性表中的數據元素。要實現對單鏈表中節點的插入、刪除與查找的功能,就要先進行的單鏈表的初始化、創建和遍歷,進而實現各功能,以下是對單鏈表節點的插入、刪除、查找功能的具體實現:

#include<stdio.h>#include<stdlib.h>#include<string.h>typedef int ElemType;/***鏈表通用類型*ElemType 代表自定義的數據類型 *struct Node *next 代表 結構體指針(指向下一個結構體,完成鏈表動作) */ typedef struct Node{ ElemType data; struct Node *next;}Node; /*==========單鏈表的初始化================*//**頭結點指針數據域設置為空 */ void initList(Node **pNode){ *pNode=NULL;}/*===========單鏈表的創建=================*//**功能實現:通過用戶不斷輸入數據,創建鏈表*利用游標倆個指針(p1,p2),將申請下的數據塊(存入用戶輸入數據),鏈接起來 */ 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");} /*===============插入節點==================*//***Node **pNode 傳入頭結點空間地址*int i 傳入要插入的結點位置 */ 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(;j<i-1;target=target->next,++j);  //不斷移動target位置,到要插入結點位置,  temp=(Node *)malloc(sizeof(Node));   //申請內存空間  temp->data=item;       //存入要存入的數據位置  p=target->next;         target->next=temp; temp->next=p; } /*===============刪除節點====================*//***刪除結點后,釋放內存空間free(temp) */ void delete_data(Node **pNode,int i){ Node *target; Node *temp; int j=1; target=*pNode; for(;j<i-1;target=target->next,++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;}

通過以上各功能的實現,希望對大家單鏈表的學習有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 耒阳市| 曲松县| 余姚市| 北碚区| 马关县| 墨江| 黄大仙区| 长宁区| 武鸣县| 乌什县| 云霄县| 兴城市| 灌云县| 阿拉善左旗| 霸州市| 敖汉旗| 揭西县| 五莲县| 沙河市| 和平县| 齐齐哈尔市| 土默特右旗| 怀仁县| 浦北县| 湾仔区| 大安市| 泰来县| 宾阳县| 平阳县| 运城市| 吉安县| 固安县| 尼玛县| 临城县| 横山县| 庐江县| 马鞍山市| 浠水县| 扎囊县| 上栗县| 朝阳市|