C: 单链表的构建(超详细图解) 您所在的位置:网站首页 单链表反序输出c语言 C: 单链表的构建(超详细图解)

C: 单链表的构建(超详细图解)

2024-06-06 08:49| 来源: 网络整理| 查看: 265

C:单链表的查找(超详细图解) C:单链表的插删(超详细图解)

C: 单链表的构建 头插法: 【样例】

对某班学生成绩排序。从键盘依次输入某班学生的姓名和成绩(一个班级人数最多不超过50人)并保存,然后按照输入顺序的反序输出每个学生的姓名和成绩。

【输入样例】 4 aaa 50 bbb 70 ccc 65 ddd 90 【输出样例】 ddd 90 ccc 65 bbb 70 aaa 50 【分析】

●构建头指针和普通指针

node *p,*first; first=new node; first->next=NULL; p=new node;

●赋值

p->name=name; p->score=score;

●把节点的next指向头指针的next

p->next=first->next;

在这里插入图片描述

●把头指针的next指向节点

first->next=p

在这里插入图片描述

●循环这个过程

for(int i=0;iname=name[i]; p->score=score[i]; p->next=first->next; first->next=p }

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

【完整代码】 #include #include using namespace std; typedef struct node { string name; int score; node* next; }node; node* create(node* head,string name[],int score[],int len); void show(node* first); int main() { int n; cin>>n; string name[n]; int score[n]; node* first; for(int i=0;i>name[i]>>score[i]; first=create(first,name,score,n); show(first); return 0; } node* create(node* first,string name[],int score[],int len) { node *p; first=new node; first->next=NULL; for(int i=0;iname=name[i]; p->score=score[i]; p->next=first->next; first->next=p } return first; } void show(node * first) { node* p = first->next; while(p != NULL){ coutnext=p; end=p; }

在这里插入图片描述 在这里插入图片描述

在这里插入图片描述

●最后加NULL

end->next=NULL;

在这里插入图片描述

【完整代码】 #include #include using namespace std; typedef struct node{ string name; int score; node* next; }node; node* create(node* head,string name[],int score[],int len); void show(node* first); int main() { int n; cin>>n; string name[n]; int score[n]; node* first; for(int i=0;i>name[i]>>score[i]; first=create(first,name,score,n); show(first); return 0; } node* create(node* first,string name[],int score[],int len) { node *end,*p; first=new node; end=first; int j; for(j=0;jname=name[j]; p->score=score[j]; end->next=p; end=p; } end->next=NULL; return first; } void show(node * first){ node* p = first->next; while(p != NULL){ cout


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有