#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;
}