1.结构体的基本用法
struct student // 定义结构体student
{
char name[20];
char sex;
float height;
float weight;
};
int main()
{
student my; // 定义变量my的类型为student型,此时可以将student理解为一种数据类型
// 只有在定义结构体变量时,系统才会去分配内存空间,而不会单独为student的结构体分配空间
cin >> my.name >> my.sex >> my.height >> my.weight;
cout << my.name << " " << my.sex << " " << my.height << " " << my.weight;
return 0;
}
2.指针和结构体
#include <iostream>
#include <cstring>
using namespace std;
struct student // 定义结构体student
{
char name[20];
char sex;
string birthday;
float height;
float weight;
};
int main()
{
student my;
student *point = &my; // 定义point为指向student结构体的指针,并将point指向my
// 此时,可借助指针point操纵my,初始化my.name、my.sex等变量
// 有了指向结构的指针,可以通过'->'访问其成员
strcpy(point->name, "Felix");
point->sex = 'M';
point->birthday = "2002-08-31";
point->height = 178;
point->weight = 64;
cout << my.name << endl;
cout << my.sex << endl;
cout << my.birthday << endl;
cout << my.height << endl;
cout << my.weight << endl;
return 0;
}
3.链表
(1)链表的建立
#include <iostream>
using namespace std;
struct Node
{
int val;
Node *next;
// 借助构造函数传值
Node(int _val) : val(_val), next(NULL) {}
/*
后面的':'的含义是:直接给成员变量赋值
等效于下面的写法:
Node(int _val)
{
val = _val;
next = NULL;
}
*/
};
int main()
{
Node *p = new Node(1); // new返回的结点1的地址,将地址赋给指针p
Node *q = new Node(2);
Node *o = new Node(3);
p->next = q;
q->next = o;
return 0;
}
(2)链表的遍历
int main()
{
Node *p = new Node(1); // new返回的结点1的地址,将地址赋给指针p
Node *q = new Node(2);
Node *o = new Node(3);
p->next = q;
q->next = o;
Node *head = p;
for(Node *i = head; i != NULL; i = i->next)
{
cout << i->val << " ";
}
return 0;
}
(3)链表的插入结点(在头结点处插入)
int main()
{
Node *p = new Node(1); // new返回的结点1的地址,将地址赋给指针p
Node *q = new Node(2);
Node *o = new Node(3);
p->next = q;
q->next = o;
Node* head = p;
// 将结点4插入到头结点处
Node* u = new Node(4);
u->next = head;
head = u;
return 0;
}
(4)链表的删除结点
注意:删除一个结点,必须要知道待删除结点的前一个结点的位置!
链表的删除,并不是将这个点物理删除,而是在遍历的时候,将这个点跳过去(调整指针的指向)
int main()
{
Node *p = new Node(1); // new返回的结点1的地址,将地址赋给指针p
Node *q = new Node(2);
Node *o = new Node(3);
p->next = q;
q->next = o;
Node *head = p;
// 删除结点
head->next = head->next->next; // head->next = p->next;
return 0;
}