数据结构-单链表(C语言版)
创建一个链表,实现:1.以头结点开始插入数据(头插法)2.以尾节点开始插入数据(尾插法)3.输出链表所存入数据 4.指定位置插入数据 5.指定位置删除数据
#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
typedef struct node{
DataType data;
struct node* portion;
}Node;
Node* init() //初始化单链表
{
Node* A = (Node*)malloc(sizeof(Node));
A->data = 0;
A->portion = NULL;
return A;
}
void headwrite(Node* A,DataType data) //头插法
{
Node* P = (Node*)malloc(sizeof(Node));
P->data = data;
P->portion = A->portion;
A->portion = P;
}
Node* findtrail(Node* A) //寻找尾节点,只有找到尾节点,才能尾插法
{
Node* P = (Node*)malloc(sizeof(Node));
P = A;
while(P->portion != NULL)
{
P= P->portion;
}
return P;
}
void trailwrite(Node* A,DataType data) //尾插法,只有找到尾节点,才能尾插法
{
Node* P = (Node*)malloc(sizeof(Node));
Node* Q = (Node*)malloc(sizeof(Node));
P = findtrail(A);
Q->data = data;
P->portion = Q;
Q->portion = NULL;
}
int deletedata(Node* A,int portion) //删除节点
{
int i = 0;
Node* P = (Node*)malloc(sizeof(Node));
Node* Q = (Node*)malloc(sizeof(Node));
P = A;
while(i < portion - 1)
{
P = P->portion;
i ++;
if(P == NULL)
{
printf("删除节点错误,请重新选择位置");
return 0;
}
}
Q = P->portion;
P->portion = Q->portion;
free(Q);
}
int insertdata(Node* A,int portion,DataType data) //指定位置插入数据
{
int i = 0;
Node* P = (Node*)malloc(sizeof(Node));
Node* Q = (Node*)malloc(sizeof(Node));
P = A;
while(i < portion - 1)
{
P = P->portion;
i ++;
if(P == NULL)
return 0;
}
if(P->portion == NULL)
{
printf("删除的位置错误\n");
return 0;
}
Q->data = data;
Q->portion = P->portion;
P->portion = Q;
}
void read(Node* A) //输出链表数据
{
Node* P = (Node*)malloc(sizeof(Node));
P = A->portion;
while(P != NULL)
{
printf("%d ",P->data);
P = P->portion;
}
printf("\n");
}
int main()
{
int i = 0;
Node* H = init();
for(i = 0;i < 10;i ++)
{
headwrite(H,i + 10); //头插法插入数据
}
read(H);//输出数据
trailwrite(H,80); //尾插法插入数据
trailwrite(H,90);//尾插法插入数据
read(H);//输出数据
deletedata(H,3);//指定位置删除数据
read(H);//输出数据
insertdata(H,4,100);//指定位置插入数据
read(H);//输出数据
free(H); //释放数据
return 0;
}