目录
Why
一、相关函数
二、程序主体及运行情况
三、总结
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");
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;
}
三、总结
链表的操作,或者说指针的操作真的很灵活。?
|