本文转载而来
https://abigailcui.blog.csdn.net/article/details/120346561?spm=1001.2014.3001.5502
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int Elemtype;
//定义结构体
typedef struct node {
Elemtype data;
struct node* next;
}LNode, * LinkList;
//1.1
//头插法建立单链表
LinkList List_HeadInsert(LinkList L) {
LNode* s; int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d", &x);
while (x != 9999) {
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
//1.2
//头插法建立不带头结点的单链表
LinkList List_HeadInsert2(LinkList L) {
LNode* s;
int x;
//L->next=NULL;这句代码放这里不对!!!
scanf("%d", &x);
while (x != 9999) {
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = NULL;
if (NULL == L) {
L = s;
}
else {
s->next = L;
L = s;
}
scanf("%d", &x);
}
return L;
}
//2.1
//尾插法建立单链表
LinkList List_TailInsert(LinkList L) {
int x;
L = (LinkList)malloc(sizeof(LNode));
LNode* s, * r = L;//这句很重要不能写最前面!!!一定要记住
scanf("%d", &x);
while (x != 9999) {
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return L;
}
//2.2
//尾插法建立不带头结点的单链表
LinkList List_TailInsert2(LinkList L) {
LNode* s, * r;
int x;
scanf("%d", &x);
while (x != 9999) {
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = NULL;
if (NULL == L) {
L = s;//将新结点位置首节点也是尾结点
r = L;
}
else {
r->next = s;
r = s;
}
scanf("%d", &x);
}
r->next = NULL;
return L;
}
//带有头结点的方法
//不管是头插还是尾插最后都要输出一下,这就需要输出函数一下
//定义一个打印函数
void PrintList(LinkList L)
{
LinkList p;
p = L->next;
printf("链表元素如下:\n");
while (p != NULL) {
printf("%d ", p->data);//记得给%D_空个格
p = p->next;
}
printf("\n");
}
//不带有头结点的方法
//不管是头插还是尾插最后都要输出一下,这就需要输出函数一下
//定义一个打印函数
void PrintList2(LinkList L)
{
LinkList p;
p = L;
printf("链表元素如下:\n");
while (p != NULL) {
printf("%d ", p->data);//记得给%D_空个格
p = p->next;
}
printf("\n");
}
int main() {
LinkList L11, L12, L21, L22;
//1.1头插法建立单链表
printf("头插法建立单链表,输入值(9999结束)\n");
L11 = List_HeadInsert(L11);
PrintList(L11);
//1.2头插法建立单链表
printf("头插法建立不带头的单链表,输入值(9999结束)\n");
L12 = List_HeadInsert2(L12);
PrintList2(L12);
//2.1尾插法建立单链表
printf("尾插法建立单链表,输入值(99999结束)\n");
L21 = List_TailInsert(L21);
PrintList(L21);
//2.2尾插法建立不带头单链表
printf("尾插法建立不带头的单链表,输入值(99999结束)\n");
L22 = List_TailInsert2(L22);
PrintList2(L22);
return 0;
}