一、代码实现
#include<stdio.h>
#include<stdlib.h>
#define NULL 0
struct node//定义节点
{
int data;//数据域
struct node *next;//链接指针域
};
struct node *head, *p, *q, *nw;//指向节点的指针
//显示链表
void disp() {
if (head == NULL) {//空表
printf("没有节点\n");
return;
}
int i = 1;
p = head;
do
{
printf("(%d)=%3d", i, p->data);//显示第一个节点的数据
p=p->next;
i++;
} while (p!=NULL);//直到表尾
printf("\n\n");
}
//插入元素
void addnode() {
int a=0,b=0;
printf("请输入插入位置的原数据 a=");
scanf_s("%d", &a);
printf("\n");
printf("请输入插入位置的新数据 b=");
scanf_s("%d", &b);
printf("\n");
nw = (struct node*)malloc(sizeof(struct node));//为数据申请一个新节点
nw->data = b;//将插入数据填入新节点
if (head == NULL) {
head = nw;
nw->next = NULL;
}
else
{
if (head->data == a) {//头节点插入位置
nw->next = head;
head = nw;
}
else
{
if (head->next == NULL) {
//原表中只有一个节点,则插入节点之后
head->next = nw;
nw->next = NULL;
}
else
{
p = head;
do
{
q = p;
p = p->next;
} while (p->data != a && p->next != NULL);
if (p->data == a) {
//找到插入位置
q->next = nw;
nw->next = p;
}
else {//找不到插入位置
p->next = nw;
nw->next = NULL;
}
}
}
}
disp();//显示插入后链表
}
//删除元素
void deleteNode() {
if (head == NULL) {
printf("空表\n");
return;
}
int a;
printf("请输入待删除的数据 a=");
scanf_s("%d", &a);
printf("\n");
if (head->data == a) {
p = head;
head = p->next;
free(p);
}
else
{
p = head;
do
{
q = p;
p = p->next;
} while (p->data != a && p->next != NULL);
if (p->data == a) {
//找到删除位置
q->next = p->next;
free(p);
}
else {
printf("找不到删除位置");
return;
}
}
disp();//显示删除后链表
}
struct Node* initializeLinkedList() {
struct node *head = NULL;
return head;
}
/* 定义链表节点 */
//struct ListNode {
// int val;
// struct ListNode *next;
//};
//
///* 初始化空链表 */
//struct ListNode* initList() {
// struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
// head->next = NULL;
// return head;
//}
int main() {
int flag = 1;//判断用户是否打算退出
int n = 0;
int i = 0;
int x = 0;
struct node* head = initializeLinkedList();
struct node* p = head;
/* 初始化空链表 */
while (flag)
{
printf("please input a number between 1 with 10\n");
scanf_s("%d",&n);
if (n >= 1 && n <= 10)
{
flag = 0;
}
}
//在循环中,修改节点的赋值方式
for (int i = 0; i < n; i++) {
addnode();
printf("\n");
}
disp();
flag = 1;
while (flag)
{
int choice = 0;
printf("-----------------------------------------\n");
printf("1.删除链表元素 2.添加链表元素 3.退出\n");
printf("-----------------------------------------\n");
scanf_s("%d", &choice);
switch (choice)
{
case 1:deleteNode();
break;
case 2:addnode();
break;
case 3:
flag = 0;
break;
default:
printf("ERROR!");
break;
}
}
return 0;
}
二、运行结果![](https://img-blog.csdnimg.cn/3c81c473dfda4949a9e58321040fb397.png)