#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}*List,Node;
//头插法
List headInsert()
{
//申请头结点
Node *head = (Node*)malloc(sizeof(Node));
head->data = 0;
head->next = NULL;
int x = 0;
//输入插入的数据,输入值为 0 时停止
printf("please input the data by headInsert(quit while data equals to 0):");
scanf("%d",&x);
while(x != 0){
Node *p = (Node*)malloc(sizeof(Node));
p->data = x;
p->next = head;
head = p;
scanf("%d",&x);
}
return head;
}
//尾插法
List tailInsert()
{
//申请头结点
Node *tail = (Node*)malloc(sizeof(Node));
tail->data = 0;
tail->next = NULL;
//由于尾插的过程中会丢失头指针地址,所以先把头指针地址储存起来
Node *head = tail;
int x = 0;
//输入插入的数据,输入值为 0 时停止
printf("please input the data by tailInsert(quit while data equals to 0):");
scanf("%d",&x);
while(x != 0){
Node *p = (Node*)malloc(sizeof(Node));
p->data = x;
tail->next = p;
p->next = NULL;
tail = p;
scanf("%d",&x);
}
return head;
}
//计算表长,不包含头结点
int lenth(const List L)
{
int count = 0;
List p = L;
while(p->next != NULL){
count++;
p = p->next;
}
return count;
}
//打印链表数据,不包含头结点
void show(const List L)
{
List p = L;
//只有头结点时,其下一个节点指向为NULL
if(p->next == NULL){
printf("it is empty");
return;
}
//打印头插法时的数据
if(p->data == 0){
while(p->next != NULL){
p = p->next;
printf("%d ",p->data);
}
}
//打印尾插法时的数据
else{
while(p->next != NULL){
printf("%d ",p->data);
p = p->next;
}
}
printf("\n");
}
//指定位置插入数据,不包含头结点
List Insert(int n,const List L)
{
//判断插入位置的合法性
if(n > lenth(L) || n < 0){
printf("out of the range,please input the place from 0 to %d\n",lenth(L));
return L;
}
List p = L;
int x = 0;
Node *s = (Node*)malloc(sizeof(Node));
while((n-1) > 0){
p = p->next;
n--;
}
printf("please insert the data that you want to:");
scanf("%d",&x);
s->data = x;
s->next = p->next;
p->next = s;
return L;
}
//指定位置删除数据,不包含头结点
List delete(int n,const List L)
{
//判断删除位置的合法性
if(n > lenth(L) || n < 0){
printf("out of the range,please delete the place from 0 to %d\n",lenth(L));
return L;
}
List p = L;
while((n-1) > 0){
p = p->next;
n--;
}
//记得动态释放内存
Node *s = p->next;
p->next = s->next;
free(s);
return L;
}
//按位置查找节点数据,不包含头结点
List searchNodeData(int n,const List L)
{
//判断查找位置的合法性
if(n > lenth(L) || n < 0){
printf("out of the range,please search the place from 0 to %d\n",lenth(L));
return L;
}
Node *s = L;
while(n > 0){
s = s->next;
n--;
}
return s;
}
void main(int argc,char *argv[])
{
//测试
/* List l = headInsert();
printf("%d\n",lenth(l));
show(l);
*/ List s = tailInsert();
// printf("%d\n",lenth(l));
show(s);
// Insert(0,s);
delete(3,s);
show(s);
Node *t = searchNodeData(3,s);
printf("%d\n",t->data);
}
单链表C语言实现
于 2022-02-03 17:21:34 首次发布