目录
一、类与结构体
1.1类的定义
类的功能:类可以把变量,数组,函数等打包在一起。
类中的变量和函数统一称为类的成员变量
关键字:class:命名
private:表示后面的内容都是私有成员变量,在类的外部都不能访问
public:表示后面的内容都是公有成员变量,在类的外部可以访问
定义示例:
#include<iostream>
using namespace std;
const int N=110;
class Person
{
private:
int age,height;
double money;
string books[N];
void add_money(double x)
{
money += x;
}
public:
string name;
int get_age()
{
return age;
}
}; //不要忘了写 “;” !!
int main()
{
return 0;
}
1.2类的调用
#include<iostream>
using namespace std;
const int N=110;
class Person
{
private:
int age,height;
double money;
string books[N];
void add_money(double x)
{
money += x;
}
public:
string name;
int get_age()
{
return age;
}
};
int main()
{
Person c;
c.name = xiaoming;
c.age =18; //错误:私有变量在外无法访问
return 0;
}
1.3结构体
结构体和类的作用是一样的
不同点在于:如果不写private和public,类默认是private,结构体默认是public
一般把代码较短,和数组相关的定义成结构体,比较复杂的定义成类。
关键字:struct
#include<iostream>
using namespace std;
const int N=110;
struct Person
{
private:
int age,height;
double money;
string books[N];
void add_money(double x)
{
money += x;
}
public:
string name;
int get_age()
{
return age;
}
};
int main()
{
Person c;
c.name = xiaoming;
return 0;
}
1.4用类或结构体构造函数
#include<iostream>
using namespace std;
struct Person
{
int age,height;
double money;
Person(int age1,int height1,double money1) //构造函数
{
age = age1;
height = height1;
money = money1;
}
};
int main()
{
Person p(18,180,100.0); //构造一个p
return 0;
}
二、指针和引用
2.1指针
指针指向存放变量的值的地址,因此我们可以通过指针来修改变量的值。
定义:*p
2.2引用
引用与指针类似,相当于给变量起了一个别名。
关键字:&
#include<iostream>
using namespace std;
char a,b;
int main()
{
int a=10;
int* p = &a;
cout<<*p<<endl; //可以通过指针来读取变量的值
*p=12;
cout<<a<<endl; //此时a等于12.可以通过指针来修改变量的值
return 0;
}
链表:
在数据结构与算法中,链表可以同时把结构体和指针复习到
#include<iostream>
using namespace std;
struct node
{
int val;
node* next;
node(int val1): val(val1),next(null){}
};
int main(){
node* p=new node(1);
node* q=new node(2);
node* o=new node(3);
p->next = q; //->:调用结构体或类里面的成员变量的时候,如果调用的是一个指针,需要用->来调用
q->next = o;
node* head = p;
//链表的遍历
for(node* i=head; i; i=i->next)
{
cout<< i->val <<endl;
}
}
具体还可以看看这篇博客:数据结构1 链表
三、例题
合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
数据范围
链表长度 [0,500]。
样例
输入:1->3->5 , 2->4->5
输出:1->2->3->4->5->5
解析
#include<iostream>
using namespace std;
class Solution{
public:
ListNode* merge(ListNode* l1,ListNode* l2)
{
auto dummy = new ListNode(-1); //先定义一个虚拟头节点
auto tail = dummy;
while(l1 && l2) //如果两条链表都不空
{
if(l1->val < l2->val)
{
tail=tail->next = l1;
l1 = l1->next;
}
else
{
tail=tail->next = l2;
l2 = l2->next;
}
}
if(l1)tail->next = l1;
if(l2)tail->next = l2;
return dummy->next;
}
}