#include<stdio.h>
#include<stdlib.h>
//单链表结点的定义
typedef struct lnode
{
int data;//数据域
struct lnode* next; //指向后继结点的指针
}node;
typedef node linklist;
//求单链表的长度
int len_list(linklist L)
{
node* p;
p = &L;
int len=0;
while(p->next != NULL)
{
p = p->next;
len++;
}
return len;
}
//头插法创建单链表
void head_insert(linklist* plist)
{
node* p;//p指针每次指向新插入的结点
plist->next = NULL;
printf("how many numbers do you what to input for the link-list?\n");
int n;
scanf("%d", &n);
printf("now, input those numbers:\n");
for(int i=0; i<n; i++)
{
p = (node*)malloc(sizeof(node));
int a;
scanf("%d", &a);
p->data = a;
p->next = plist->next;
plist->next = p;
}
return;
}
//尾插法创建单链表
void tail_insert(linklist* plist)
{
node* p;//p指针每次指向新的要插入的结点
plist->next = NULL;
node* tail;//tail指针每次指向最后的结点
tail = plist;
printf("how many numbers do you what to input for the link-list?\n");
int n;
scanf("%d", &n);
printf("now, input those numbers:\n");
for(int i=0; i<n; i++)
{
p = (node*)malloc(sizeof(node));
int a;
scanf("%d", &a);
p->data = a;
p->next = NULL;
tail->next = p;
tail = p;
}
return;
}
//在单链表插入某个元素
void insert_list(linklist* plist, int i, int e)
{
if(i<=0 || i>(len_list(*plist) + 1))//判断是否合法
{
printf("you can not insert in this place!\n");
return;
}
node *q = (node*)malloc(sizeof(node));//寻找该插入的位置的前一个节点
q = plist;
int j=1;
while(j < i)
{
q = q->next;
j++;
}
node *p = (node*)malloc(sizeof(node));//新插入的结点
p->data = e;//赋值
p->next = q->next;//后边连上
q->next = p;//前边连上
return;
}
//删除单链表第几个元素
void delete_list(linklist* plist, int i)
{
if(i<=0 || i>len_list(*plist))
{
printf("you can not delete this element!\n");
return;
}
node* p = plist;
int j=1;
while(j < i)
{
p = p->next;
j++;
}
node* q = p->next;//指向被删除的元素,待会释放它
p->next = p->next->next;//逻辑上删除
free(q);//物理上删除
return;
}
//查找单链表某个位置上的元素
void search_element(linklist L, int x)
{
if(x<=0 || x>len_list(L))
{
printf("error! beyond the mark!\n");
return;
}
node* pnode = (node*)malloc(sizeof(node));
pnode = &L;
for(int i=1; i<=x; i++)
{
pnode = pnode->next;
}
printf("the element of this place is:%d", pnode->data);
return;
}
//查找某个元素在单链表的位置
void search_placement(linklist L, int e)
{
node* pnode = (node*)malloc(sizeof(node));
pnode = &L;
pnode = pnode->next;
int loc = 1;
for(int i=0; i<len_list(L); i++)
{
if(pnode->data == e)
{
printf("the placement of this element is:%d\n", loc);
return;
}
else
{
pnode = pnode->next;
loc++;
}
}
}
//打印单链表
void print_list(linklist L)
{
printf("the list is :\n");
node* p = &L;
while(p->next != NULL)
{
printf("%d ", p->next->data);
p = p->next;
}
printf("\n");
}
int main()
{
linklist L;
// head_insert(&L);//头插法创建单链表
// print_list(L);
// tail_insert(&L);//尾插法创建单链表
// print_list(L);
// insert_list(&L, 2, 999);//在某位置插入某元素
// print_list(L);
// delete_list(&L, 1);//删除某位置的元素
// print_list(L);
// int len = len_list(L);//求单链表的长度
// printf("the length of this list is: %d \n", len);
// search_element(L, 2);//查找某元素的位置
// search_placement(L, 5);//查找某个元素的位置
return 0;
}
单链表的定义以及基本操作 超详细!
最新推荐文章于 2024-04-19 17:19:21 发布