c++结构体数组的初始化
#include <iostream>
#include <string.h>
using namespace std;
struct student{
int num;
char name[20];
float score[10];
};
void print(student stu){
cout<<stu.name<<endl;
cout<<stu.num<<endl;
cout<<stu.score[0]<<endl;
cout<<stu.score[1]<<endl;
}
int main(){
//定义一个叫stu的结构体
struct student stu;
strcpy(stu.name,"fish.com");//stu.name="fish.com"
stu.score[0]=90;
stu.score[1]=90;
stu.score[2]=90;
print(stu);
}
但是结构体每次定义新节点都要写个struct很麻烦
//声明结构类型
typedef struct node{
int data;
struct node *next;
}ElemSN;//struct类型的新别名
//定义新的链表指针的时候就可以 用
或者使用指针
#include <iostream>
#include <string.h>
using namespace std;
struct student{
int num;
char name[20];
float score[10];
};
void print(student *stu){
cout<<stu->name<<endl;
cout<<stu->num<<endl;
cout<<stu->score[0]<<endl;
cout<<stu->score[1]<<endl;
}
int main(){
//定义一个叫stu的结构体
struct student stu;
strcpy(stu.name,"fish.com");//stu.name="fish.com"
stu.score[0]=90;
stu.score[1]=90;
stu.score[2]=90;
//传地址
print(&stu);
}
建立链表
#include <iostream>
#include <string.h>
using namespace std;
struct student{
int num;
float score;
struct student *next;
};
int main(){
//定义一个 四个结构体 三个节点 一个头指针
struct student a,b,c,*head;
a.num=111;
a.score=11;
b.num=222;
b.score=222;
c.num=333;
c.score=33;
head=&a;
a.next=&b;
b.next=&c;
c.next=NULL;//表示链表结束
while(head!=NULL){
cout<<head->num<<","<<head->score<<endl;
head=head->next;
}
}
建立动态链表
我写的头插法哈哈
#include <iostream>
#include <string.h>
using namespace std;
#define LEN sizeof(struct student)//结构大小
struct student{
int num;
float name;
struct student *next;
};
//创建链表
struct student add(student *head);
//打印链表
void print(student* head);
void shouye(student *head);
struct student add(student *head){
student *a;
a=(struct student *)malloc(LEN);
cin>>a->num>>a->name;
//判断学号是否为0 不是则录入
if(a->num==0){
cout<<"no";
shouye(head);
}else{
//头插
a->next=head->next;
head->next=a;
}
shouye(head);
//判断头指针是否指向空 不是则头插
return *head;
}
void print(student* head){
while(head!=NULL){
cout<<head->num<<","<<head->name<<endl;
head=head->next;
}
}
void shouye(student *head){
int option;
cout<<"选1 打印 选二 添加";
cin>>option;
switch (option)
{
case 1:
/* code */
print(head);
break;
case 2:
add(head);
default:
break;
}
}
int main(){
struct student a,b,c,*head,first;
a.num=111;
a.name=11;
b.num=222;
b.name=222;
c.num=333;
c.name=33;
head=&first;
first.next=&a;
a.next=&b;
b.next=&c;
c.next=NULL;//表示链表结束
cout<<head->next->name<<endl;
shouye(head);
}