更新时间:2022-06-19 03:20:22
数据在计算机程序中都是存储在内存空间中的.
#include <stdio.h>
#include <stdlib.h>
#include <MATH.h>
typedef struct linklist
{
int data;
struct linklist *next; //单链表
}linknode,*linklistp;
//返回头部
linklistp insert_head(linklistp head,linklistp newnode){
newnode->next=head;
head=newnode;
return head;
}
linklistp insert_tail(linklistp head,linklistp newnode){
if(head==NULL){
head=newnode;
}else{
linklistp temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;
}
return head;
}
//删除节点
linklistp list_delete(linklistp head,int a){
linklistp temp=head;
//1.temp为空,返回NULL
if(temp==NULL){
printf("链表为空\n");
return NULL;
}
//2.正好是首节点
if(temp->data==a){
head=head->next;
free(temp);
return head;
}
//3.不在首节点
linklistp prev=head;
temp=head->next;
while(temp!=NULL&&temp->data!=a){
prev=temp;
temp=temp->next;
}
//3.1 没找到
if(temp==NULL){
printf("不存在\n");
return NULL;
}
prev->next=temp->next;
return head;
}
//查找第i个元素
int getElem(linklistp head,int i,int a){
if (head->next==NULL)
{
printf("link list is NULL");
return 0;
}
linklistp temp=head;
int j=0;
while(temp->next&&j<i){
temp=temp->next;
++j;
}
if(!temp||j>i){
printf(" 不存在第i个元素\n");
}
a=temp->data;
return a;
}
//判断链表是否为空
_Bool isEmpty(linklistp head){
if (head->next==NULL)
{
printf("链表为空\n");
return 1;
}
return 0;
}
void output(linklistp head){
linklistp temp=head;
while(temp){
printf("%d\t", temp->data);
temp=temp->next;
}
printf("\n");
}
int main(){
linklistp head=NULL;
for (int i = 0; i < 10; ++i)
{
/* code */
linklistp newnode=(linklistp)malloc(sizeof(linknode));
newnode->data=i*10+2;
newnode->next=NULL;
head=insert_head(head,newnode);
}
output(head);
printf("*********删除节点*******\n");
int data=0;
printf("请输入要删除的数据:\n");
scanf("%d",&data);
linklistp temp=list_delete(head,data);
if (temp==NULL)
{
printf("def failture or not has this node");
}else{
head=temp;
output(head);
}
printf("**************************\n");
printf("enter the num you want to find:\n");
printf("%d\n",getElem(head,2,data));
return 0;
}