其他分享
首页 > 其他分享> > 数据结构之单链表

数据结构之单链表

作者:互联网

//头插 尾插 删除 查询 单链表
#include<stdio.h>
#include<stdlib.h>

#define ElemType int

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

//创造头节点,本人比较喜欢有头结点的,方便
Node *createHead()
{
Node *head=(Node*)malloc(sizeof(Node));
head->next=NULL;
head->data=0;
return head;
}

//创造节点函数,待会有什么地方需要创造节点可以直接调用,不用写一堆
Node *createNewNode(ElemType a)
{
Node *newNode=(Node*)malloc(sizeof(Node));
newNode->data=a;
newNode->next=NULL;

return newNode;//将节点地址传过去,后续操作要用
}

//头插法 画图就很好理解了
void insert_Node(Node *Head,ElemType target)
{
Node *newNode;
newNode=createNewNode(target);//这就需要创造节点,直接调用函数
newNode->next=Head->next;//先将头结点的下一位元素的地址赋值给新节点的next属性
Head->next=newNode;//再将头节点的next属性赋值上新节点的地址
}

//尾插法 尾插和头插相差不算大,还简单一些,因为尾插的新节点next属性不用赋值,新节点的暂时后续没有节点
Node* insert_tail(Node *tail,ElemType target)
{
Node *newNode;
newNode=createNewNode(target);
tail->next=newNode;

return newNode;
}

//按值查找
Node* query_target(Node *head,ElemType target)
{
Node *tmp=NULL;
Node *pMove;
pMove=head->next;
while(pMove)
{
if(pMove->data==target)
{
tmp=pMove;
printf("存在\n");
return tmp;
}
pMove=pMove->next;
}
//空表
//if(pMove==NULL&&tmp==NULL)//为什么这里得判断两个空呢?因为我们得防止是空表
//{
printf("不存在\n");
return tmp;
//}
}

//按下标查找
Node *query_index(Node *head,ElemType index)
{
int tmp_count=0;
Node *pMove;
pMove=head;
while(pMove->next)
{
if(tmp_count==index)
{
printf("找到数值%d,下标为%d\n",pMove->data,tmp_count);
return pMove;
}
tmp_count++;
pMove=pMove->next;
}
if(pMove==NULL&&index!=tmp_count)
{
printf("未找到该下标\n");
return NULL;
}
}

//根据提供的下标插入结点
void random_insert(Node *head,int index,ElemType target)
{
Node *pMove;
pMove=query_index(head,index);//调动函数寻找下标为index-1的地址
Node *newNode=createNewNode(target);
newNode->next=pMove->next;
pMove->next=newNode;

}

//删除节点
void delete_node(Node *head,int index)
{
Node *pMove;
pMove=head;//和显示函数的不一样。这里不能是head->next了,因为我们要想删除头节点的下一个节点,也就是存储数据的第一个节点,必须要到头节点的地址

int tmp_count=0;

while(pMove)
{
if(tmp_count==index)//因为你要的是删除index的位置,所以在index-1处停下,(index-1)->next就是index
{
Node *target=pMove->next;//index删除目标
pMove->next=target->next;//用删除目标的下一个节点把删除目标替换,删除成功
}

tmp_count++;
pMove=pMove->next;
}
}

void print_list(Node *head)
{
Node *pMove;
pMove=head->next;

while(pMove)
{
printf("%d ",pMove->data);
pMove=pMove->next;
}
printf("\n");
}


int main()
{
//尾插法
Node *Head;
Head=createHead();

Node *latest=NULL;

printf("尾插数值:\n");
ElemType a;
scanf("%d",&a);
latest=insert_tail(Head,a);
print_list(Head);

while(1)
{
printf("尾插数值:\n");
scanf("%d",&a);
latest=insert_tail(latest,a);//因为是尾插法,所以得有最新的尾元素地址latest
print_list(Head);


printf("插入一个数值,下标为0,值为5\n");
random_insert(Head,0,5);
print_list(Head);

}


return 0;
}

标签:Node,index,head,单链,next,newNode,pMove,数据结构
来源: https://www.cnblogs.com/qingfeng66/p/16483027.html