本文采用插入采用头插法,删除采用任意位置删除。
什么是链表:链表就是结构体变量与结构体变量通过指针连接在一起。
单链表主要是数据域和指针域构成。
单链表的编程思路:动态内存申请+模块化设计
1.动态内存申请就是为了使得结构体指针变为结构体变量。
2.模块化设计
(1)表头
(2)节点
(3)插入节点
(4)删除节点
(5)打印遍历链表
下面直接展示完整程序:
#include"stdio.h"
#include"stdlib.h"
struct node
{
int data;
struct node* next;
};
struct node* createlist()
{
struct node* headnode = (struct node*)malloc(sizeof(struct node));
headnode->next = NULL;
return headnode;
}
struct node* createnode(int data)
{
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
void printlist(struct node* headnode)
{
struct node* pmove = headnode->next;
while(pmove)
{
printf("%d\t",pmove->data);
pmove = pmove->next;
}
printf("\n");
}
void insernodebyhead(struct node* headnode,int data)
{
struct node* newnode = createnode(data);
newnode->next = headnode->next;
headnode->next = newnode;
}
void deletenodebyappoin(struct node* headnode,int posdata)
{
struct node* posnode = headnode ->next;
struct node* posnodefront = headnode;
if(posnode==NULL)
printf("无法删除\n");
else
{
while(posnode->data !=posdata)
{
posnodefront=posnode;
posnode=posnodefront->next;
if(posnode==NULL)
{
printf("没有找到相关信息,无法删除\n");
break;
}
}
posnodefront->next=posnode->next;
free(posnode);
}
}
int main()
{
struct node* list=createlist();
insernodebyhead(list,1);
insernodebyhead(list,2);
insernodebyhead(list,3);
printlist(list);
deletenodebyappoin(list,1);
printlist(list);
// system("pause");
return 0;
}
最后实现结果: