关于C语⾔单链表的⼀些操作函数⽬录
Why
最近学习的数据结构与算法,作为⼩⽩⾃然是从基础开始,也即线性结构-单链表
⼀、相关函数
List* creatlist(int n)    //产⽣链表的函数,n决定链表长度
{
List* p,* head,* q = NULL;
int a = 0;
for (int i = 0; i < n; i++){
if(scanf("%d", &a));
p = (List*)malloc(sizeof(List));
if (p != NULL){
p->data = a;
p->next = NULL;
}
if (head == NULL){
head = p;
q = p;
}
else{
q->next = p;
q = p;
}
}
return head;
}
void showlist(List* L1)    //打印链表的函数
{
List* p = NULL;
p = L1;
while (p->next != NULL){
printf("%d ", p->data);
p = p->next;
}
printf("%d ", p->data);
}
List* insertlist(List* L1, int m, int n)  //函数实现链表元素的插⼊,m控制所插⼊元素的个数,n⽤来控制插⼊的节点{
List* p = L1;
for (int i = 0; i < n-1; i++){
p = p->next;
}
List* q = NULL;
q = creatlist(m);  //产⽣的插⼊链表以q为头
List* t = NULL;
t = q;
while (t->next != NULL){
t = t->next;
}
t->next = p->next;
p->next = q;
return L1;
}
List* deletelist(List* L1, int n)  //函数实现链表元素的,第n个节点的删除
{
List* t, *q = NULL;
List* p = L1;
for(int i = 0; i < n-1; i++){
p = p->next;
};
if(p){
q = p->next;
t = q->next;
p->next = t;
}
return L1;
}
List* link_reversed_order(List* p_head)      //实现链表的倒序
{
List* pf = NULL, * pb = NULL, * tmp = NULL;
pf = p_head;
if (p_head == NULL) {
printf("链表为空,不需要逆序!\n");
return p_head;
}
else if (p_head->next == NULL) {
printf("链表只有⼀个节点,不需要逆序!\n");
return p_head;
}
else {
pb = pf->next;
p_head->next = NULL;
while (pb != NULL){
tmp = pb;
pb = pb->next;
tmp->next = pf;
pf = tmp;
}
p_head = pf;
return p_head;
}
}
⼆、程序主体及运⾏情况
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 20
typedef int Elemtype;
struct number {
Elemtype data;
struct number* next;
};
typedef struct number List;
List* creatlist(int n);    //产⽣链表的函数,n决定链表长度
void showlist(List* L1);    //打印链表的函数, n⽤来控制打印的初始位置
List* insertlist(List* L1, int m, int n);//函数实现链表元素的插⼊,m控制所插⼊元素的个数,n⽤来控制插⼊的节点List* deletelist(List* L1, int n);  //函数实现链表元素的,第n个节点的删除
List* link_reversed_order(List* p_head);//函数实现链表元素的倒序输出
int main(void)
{
int a, b, m, n = 0;
List* L, * L1, * L2, * L3 = NULL;
printf("输⼊所要创建的链表元素的个数:\n");
scanf("%d", &a);
printf("现在依次输⼊链表元素:\n");
L = creatlist(a);
printf("请输⼊插⼊元素的节点:\n");
scanf("%d", &n);
printf("请输⼊插⼊元素的个数:\n");
scanf("%d", &m);
printf("现在依次输⼊所要插⼊的元素:\n");
L1 = insertlist(L, m, n);
printf("插⼊元素后的链表为:\n");
c语言listinsert函数
showlist(L1);
printf("\n");
printf("输⼊要删除的节点:\n");
scanf("%d", &b);
L2 = deletelist(L1, b);
printf("删除节点后的链表为:\n");
showlist(L2);
printf("\n");
printf("输出上⼀链表的倒序结果为:\n");
L3 = link_reversed_order(L2);
showlist(L3);
return 0;
}
链表的操作,或者说指针的操作真的很灵活。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。