#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
typedef struct LNode
{
int data;
struct LNode* next;
}LNode ,*Linklist ;
//不带头节点
//bool InitList(LNode *&L) //初始化单链表
//{
// L = NULL; //空链表,暂时没有任何节点,以防止又其他脏数据
// cout << "1" << endl;
// return true;
//}
//带头节点的单链表
bool InitList(LNode*& l)
{
l = (LNode*)malloc(sizeof(LNode));
if (l == NULL)
return false;
l->next = NULL;
return true;
}
//代码测试
//头插法创建单链表 ( 每个新插入的数据都在头结点的后面)
Linklist Creatlist1(Linklist& l)
{
LNode* s; int x;
l = (LNode*)malloc(sizeof(LNode));
if (l)
{
l->next = NULL;
}
cout << "请输入节点的值";
//scanf("&d", &x); 不兼容
cin >> x;
while (x!= 1000) //输入1000时自动退出循环
{
s = (LNode*)malloc(sizeof(LNode)); //创建一个新的节点
if (s) //判断s是否为空
{
s->data = x;
s->next = l->next;
}
l->next = s;
cout << "请再次输入节点的值";
// scanf("%d", &x); 不兼容
cin >> x;
}
l->next = NULL;
return l;
}
//尾插法创建点链表
Linklist Creatlist2(Linklist &l)
{
LNode* s, * r = l; int x;
l = (LNode*)malloc(sizeof(LNode));
cout << "请输入节点的值 :";
cin >> x;
while (x != 1000)
{
s = (LNode*)malloc(sizeof(LNode));
if (s && r) {
s->data = x;
r->next = s;
r = s;
}
cout << "请再次输入节点的值 :";
cin >> x;
}
if (r)
{
r->next = NULL;
}
return l;
}
//按照顺序输出单链表
void Getlist(Linklist l)
{
//LNode *p = NULL;
LNode* p = l->next; //将头结点赋给一个指针
while (p) //当p为空时退出
{
cout << p->data;
cout << " ";
p= p->next;
}
cout << endl;
}
void Getlist2(Linklist &l)
{
//LNode *p = NULL;
LNode* a = l->next; //将头结点赋给一个指针
while (a) //当p为空时退出
{
cout << a->data;
cout << " ";
a = a->next;
}
cout << endl;
}
Linklist LocateElem(Linklist l, int e)
{
LNode *p = l->next;
while (p != NULL && p->data != e)
{
p = p->next;
}
return p;
}
void test()
{
Linklist l;
InitList(l);
Creatlist1(l);
//Creatlist2(l);
int i; LNode* p;
cout << "请输入查询的数据" << endl;
cin >> i;
p = LocateElem(l, i);
if (p)
{
cout << p->data << endl;
}
//Getlist(l);
//Getlist2(l);
//cout << "1" << endl;
}
int main()
{
test();
system("pause");
return 0;
}
你链表是断的
链表创建和遍历参考一下这篇。
https://ask.csdn.net/questions/7424206?spm=1010.2135.3001.5893
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!
速戳参与调研>>>https://t.csdnimg.cn/Kf0y