数据结构练习笔记——输出单链表中的数据并统计单链表中的元素个数
输出单链表中的数据并统计单链表中的元素个数
【问题描述】下面程序中createList函数的功能是创建若干个整数的带头结点的单链表存储结构。
getLength函数的功能是求解单链表中元素的个数,printLst函数的功能是将单链表中各个整数以空格间隔顺序输出。
【输入形式】若干整数以空格间隔
【输出形式】两行。第一行:单链表中的整数以空格间隔输出;第二行:单链表中元素的个数
【样例输入】1 2 3 4 5
【样例输出】
1 2 3 4 5
5
#include <iostream>
#include <cstdlib>
using namespace std;
struct LNode {
int data;
LNode *next;
};
void createList(LNode *&h) {
int num;
LNode *p,*r;
h=new LNode;
h->next=NULL;
r=h;
while(cin>>num) {
p=new LNode;
p->data=num;
r->next=p;
r=p;
}
r->next=NULL;
}
//----------------------------
void printList(LNode* L) {
LNode* p=L->next;
while(p) {
cout<<p->data<<" ";
p=p->next;
}
cout<<"\n";
}
int getLength(LNode* L) {
LNode* p=L->next;
int count=0;
while(p) {
count++;
p=p->next;
}
return count;
}
//----------------------------
int main() {
LNode *L;
createList(L);
printList(L);
cout<<getLength(L);
return 0;
}
记录一些数据结构学习过程的习题代码,便于日后查看。如有错误,欢迎交流指正。

浙公网安备 33010602011771号