C說話之單鏈表的拔出、刪除與查找。本站提示廣大學習愛好者:(C說話之單鏈表的拔出、刪除與查找)文章只能為提供參考,不一定能成為您想要的結果。以下是C說話之單鏈表的拔出、刪除與查找正文
單鏈表是一種鏈式存取的數據構造,用一組地址隨意率性的存儲單位寄存線性表中的數據元素。要完成對單鏈表中節點的拔出、刪除與查找的功效,就要先輩行的單鏈表的初始化、創立和遍歷,進而完成各功效,以下是對單鏈表節點的拔出、刪除、查找功效的詳細完成:
#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;
}
經由過程以上各功效的完成,願望對年夜家單鏈表的進修有所贊助。