数据结构之单链表

本文介绍了一个简单的链表操作实现,包括链表初始化、插入、删除等基本功能,并提供了完整的C++代码示例。通过交互式的命令行界面,用户可以选择进行插入或删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <windows.h>
#include <cstdlib>
using namespace std;
#define OK 1
#define ERROR 0
typedef struct LNode
{
int date;
struct LNode *next;
}LNode, *LinkList;
LinkList initList_L(LinkList&L, int n)//链表初始化
{
LNode *p, *q;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
p = (Lode*)malloc(sizeof(LNode));
p = L;
q = (Lode*)malloc(sizeof(LNode));
L->next = q;
q->next = NULL;
int i;
for (i = 1; i <= n; i++)
{
p = p->next;                        //指针后移
q = (Lode*)malloc(sizeof(LNode));
cin >> p->date;//输入数据
q->next = p->next; //接入结点
p->next = q;
q = p->next;
q->next = NULL;
}
return L;
}
int ListInsert_L(LinkList&L, int i, int E)//链表插入
{
LNode *p, *q;
p = (LNode*)malloc(sizeof(LNode));
p = L;
int j = 0;
while (p&&j < i - 1)
{
p = p->next;
j++;
}
if (!p || j>i - 1) return ERROR;
q = (LinkList)malloc(sizeof(LNode));
q->date = E;
q->next = p->next;
p->next = q;
return OK;
}
int ListDelete_L(LinkList&L, int i, int E)//链表删除
{
LNode *p, *q;
p = (LinkList)malloc(sizeof(LNode));
p = L;
int j = 0;
while (p&&j < i - 1)
{
p = p->next;
j++;
}
if (!p->next || j >i - 1) return ERROR;
q = (LinkList)malloc(sizeof(LNode));
q = p->next;
p->next = q->next;
E = q->date;
free(q);
return OK;
}
void Listdisplay_L(LinkList&L)//显示
{


LinkList p;
p = L;
p = p->next;
while (p->next!= NULL)
{
cout << p->date << " ";
p = p->next;
}


}
int main()
{
LinkList L;
int M;
cout << "请按键选择————————(0)插入————————(1)删除" << endl;
cin >> M;
system("cls");
switch (M)
{
case 0:
{int N, J, E, k;
cout << "请输入链表中元素的个数:" << endl;
cin >> N;
cout << "请输入链表中的元素:" << endl;
initList_L(L, N);
cout << "请输入插入元素的位置:" << endl;
cin >> J;
cout << "要插入的元素:" << endl;
cin >> E;
ListInsert_L(L, J, E);
Listdisplay_L(L);
cin >> k;
break; }


case 1:
{int a, b, c;
cout << "请输入链表中元素的个数:" << endl;
cin >> a;
cout << "请输入链表中的元素:" << endl;
initList_L(L, a);
cout << "请输入要删除元素的位置:" << endl;
cin >> b;
cout << "要删除的元素:" << endl;
cin >> c;
ListDelete_L(L, b, c);
Listdisplay_L(L);
break; }
}
system("pause");
return 0;


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值