C/C++语法:(四)类与结构体
算法题中使用的类知识很少,所以没啥好写的.类与结构体的主要区别在于,如果不定义成员是公有或私有,类中默认设置为private,而结构体中默认设置为public.以下随便写点结构体语法,背过就完事了.
1.结构体
struct person{
int age, height;
double money;
Person(){} //无参构造函数
Person(int _age, int _height): age(_age); //有参构造的快捷写法,且运行效率高一点
Person(int _age, int _height, double _moeny) : age(_age), height(_height), money(_money){}
};//分号记得要写
常用结构体定义单链表:
struct Node{
int val;
Node *next;
Node(int _val) : val(_val), next(NULL){}
};
int main(){
Node *p = new Node(1); //使用new返回的是地址
Node *q = new Node(2); //auto q = new Node(2);
Node *o= new Node(3); //auto q = new Node(2);
p->next = q;
q->next = o;
Node *head = p;
//遍历链表
for (Node *i = head; i; i = i->next)
cout << i->val << endl;
在链表首部中插入一个新结点:
Node *u = new Node(4);
u->next = head;
head = u;
注意以下写法是错误的:
ListNode *vir = new ListNode(-1), tail = vir;
请老老实实写成:
ListNode *vir = new ListNode(-1);
ListNode *tail = vir;
或者你不愿意写这么长,也可以写成:
auto vir = new ListNode(-1), tail = vir;
空结点的三种写法:
NULL
nullptr
0
本文算法思想源于Acwing,特此注明。

浙公网安备 33010602011771号