C++
链表数据类型不仅包含要存储要包含的数据结构,还需要一个指向另一个相同类型结点的指针
假设每个结点存储 类型为string的 数据项 可以有如下 声明
struct listnode
{
string name;
listnode *next1;
};
listnode就是存储在链表中的结点的类型,结构成员name是结点数据部分,另一个结构成员next1则是listnode的指针,它是指向下一个结点的后继指针。
listnode包含指向相同类型数据结构的指针,包含对自身引用的类型。
声明数据类型表示结点后,即可定义初始为空的链表,方法
listnode *head=nullptr;
创建一个链表 包含一个结点 储存值为liyang
head=new listnode;//分配新节点
head->value="liyang";//存储值
head->next=nullptr;//链表结尾值为空
创建完链表的第一个结点后,创建链表的第二个结点,储存gaofushuai
使用第二个指针指向新的结点(储存高富帅)
listnode *dierge =new listnode;
dierge->name="高富帅";
dierge->next1=nullptr;//第二个结点是链表的结尾
head->next=dierge;//第一个结点指向第二个结点
通过后继指针见第二个结点的next1设置为nullptr,使第二个结点成为链表的末尾;通过head->next1=dierge,将链表头的后继指针修改为第二个结点。
#include <iostream>
using namespace std;
struct ListNode
{
string name;
ListNode* next1;
};
int main()
{
ListNode* head = nullptr;
// Create first node with 12.5
head = new ListNode; // Allocate new node
head->name = "李阳"; // Store the value
head->next1 = nullptr; // Signify end of list
// Create second node with 13.5
ListNode* secondPtr = new ListNode;
secondPtr->name = "张三";
secondPtr->next1 = nullptr; // Second node is end of list
head->next1 = secondPtr; // First node points to second
// Print the list
cout << "First item is " << head->name << endl;
cout << "Second item is " << head->next1->name << endl;
return 0;
}