- 创建链表
//利用链表创建三个学生的信息,学生信息包括姓名和年龄,输出名为kaka学生的年龄
#include<iostream>
using namespace std;
//第一步,创建结构体
struct student
{
char name[20];
int age;
student *next; //第二步,在节点数据中添加一个指针节点数据类型的指针next
};
int main()
{
// 链表创建
student c = { "Terry",30,NULL };//尾结点的指针为null
student b = { "kaka",27,&c };
student a = { "merry",23,&b };
student *head = &a; //头指针,指向a
//链表创建完成
//使用指针访问元素
student *pointer = head;
while (pointer) { //遍历链表
if (strcmp(pointer->name,"kaka") == 0) { //匹配
cout << pointer->name << " " << pointer->age << endl;
break;
}
pointer = pointer->next;
}
if (pointer == NULL) {
cout << "没有找到" << endl;
}
return 0;
}
2.增加一个链表
//定义控制台应用程序的入口
//利用链表创建三个学生的信息,学生信息包括姓名和年龄,输出名为kaka学生的年龄
#include<iostream>
using namespace std;
//第一步,创建结构体
struct student
{
char name[20];
int age;
student *next; //第二步,在节点数据中添加一个指针节点数据类型的指针next
};
int main()
{
student c = { "Terry",30,NULL };//尾结点的指针为null
//这里增加一个学生D
student b = { "kaka",27,&c };
student a = { "merry",23,&b };
student *head = &a; //头指针,指向a
student d = { "likai",21,NULL }; ///因为一开始不知道,先设为NULL
//链表创建完成
//插入一个d
student *before = head;
student *pointer = before->next;
while (before) { //遍历链表,在b后插入一个d
if (strcmp(before->name, "kaka") == 0) { //匹配
d.next = pointer; // 第一步
before->next = &d; //第二步
break;
}
before = pointer;
pointer = before->next;
}
cout << "插入新学生之后,学生链表为:" << endl;
pointer = head; //遍历输出
while (pointer) {
cout << pointer->name << pointer->age << endl;
pointer = pointer->next;
}
system("pause");
return 0;
}
3.删除一个链表
//利用链表创建三个学生的信息,学生信息包括姓名和年龄,输出名为kaka学生的年龄
#include<iostream>
using namespace std;
//第一步,创建结构体
struct student
{
char name[20];
int age;
student *next; //第二步,在节点数据中添加一个指针节点数据类型的指针next
};
int main()
{
//链表创建
student c = { "Terry",30,NULL };//尾结点的指针为null
student b = { "kaka",27,&c };
student a = { "merry",23,&b };
student *head = &a; //头指针,指向a
//删除b
student *before = head;
student *pointer = before->next;
while (before) { //遍历链表,在b后插入一个d
if (strcmp(before->name, "merry") == 0) { //匹配
before->next = pointer->next;
break;
}
before = pointer;
pointer = before->next;
}
cout << "删除新学生之后,学生链表为:" << endl;
pointer = head; //遍历输出
while (pointer) {
cout << pointer->name << pointer->age << endl;
pointer = pointer->next;
}
system("pause");
return 0;
}
4.c++中struct构造函数
https://blog.csdn.net/a_forever_dream/article/details/88867801
struct node{
node(int c):x(0),y(c){}//注意这对象征性地大括号不能丢
//这是构造函数,类似于node(int c){ x= 0;y=c;}
int x,y;
};
用法:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {} //struct初始化
};
//加了构造函数得这样创建链表
ListNode b(1);
ListNode a(2);
a.next = &b;