接上一篇,我们继续聊聊单链表!
这一篇总共介绍三个事情–对应三个单链表操作:
- 查找单链表结点个数到底有几个?//心中有数–find
- 判断一个数据是否在链表中?//看看是否有自己想要的–select
- 查询任意节点的数据是多少?//随便看任意结点的数据–read
查找『单链表中结点数量』–find
#include<iostream> using namespace std; struct Node { int data; Node *next; }; Node *head, *p, *r;//Node类型的三个指针:头指针、中间指针和尾指针 int x,y; int find(Node *head){ int n = 0; p = head; while (p != NULL) { n += 1; p = p->next; } return n; } int main(){ cin >> x; head = new Node;// r = head;// while (x != -1) { p = new Node;// cin >> y; p ->data = y;// p ->next = NULL;// r ->next = p;// r = p;// cin >> x; } cout <<"这个单链表的结点数量为"<<find(head)<<endl; return 0; }
上面的find函数拿到的节点数不含头结点!
总节点总数量+1即可查找『数据域的值满足一定条件的结点』–select
告诉你第几个结点,请你告诉我那个结点的数值是多少!#include<iostream> using namespace std; struct Node { /* 定义数值域和指针域 */ int data; Node *next; }; Node *head, *p, *r;//Node类型的三个指针:头指针、中间指针和尾指针 默认值为NULL int x,y; int main(){ cin >> x; head = new Node;//动态申请头结点地址 r = head;//指针赋值,头尾为同一地址 while (x != -1) { /* p结点的定义 */ p = new Node;//动态申请新新结点p cin >> y; p ->data = y;//给p结点的数值域赋值 p ->next = NULL;//给p结点的指针域赋空值 /* 与其他结点进行关联 */ r ->next = p;//p结点的地址赋值给r结点的next,尾结点的next指向p结点--链接在一起 r = p;//p结点的地址与尾结点的地址一致,地址替换了!! cin >> x; } p = head->next;//头结点的地址赋值给p--与头结链接在一起 int z; cout << "输入你要查找的数据"<<endl; cin >> z; while ((p->data != z) && (p->next != NULL)) p = p->next; if(p->data == z) cout << "找到了"; else cout << "没找到"; return 0; } ```
大家思考一下如何把查找部分的代码封装成一个函数,实参是z
具体如下:
void select(int w){
while ((p->data != w) && (p->next != NULL))
p = p->next;
if(p->data == w)
cout << "找到了";
else
cout << "没找到";
}
输出『任意一个节点的数据域的值』–read
告诉你第几个结点,请你告诉我那个结点的数据是多少!#include<iostream> using namespace std; struct Node { int data; Node *next; }; Node *head, *p, *r; int x,y; void read(Node *h,int v){ Node *d; int w; d = h->next; w = 1;//为什么从1开始? while ((d != NULL)&&(w < v)) { /* 从第头结点开始找起 */ d = d->next; w++; } if((d != NULL) && (w == v)) printf("%d\n", d->data); else printf("这个结点或者数据不存在"); } int main(){ cin >> x; head = new Node;//动态申请头结点地址 r = head;//指针赋值,头尾为同一地址 while (x != -1) { /* p结点的定义 */ p = new Node; cin >> y; p ->data = y; p ->next = NULL; /* 与其他结点进行关联 */ r ->next = p; r = p; cin >> x; } p = head->next; int z; cout << "输入你要读取第几个结点的数据(头结点除外)"<< endl; cin >> z; read(head, z); return 0; } ```