C++ 实现链表的例子
时间: 2024-01-14 22:19:33 浏览: 31
以下是一个简单的C++链表实现的例子:
```cpp
#include <iostream>
using namespace std;
// 链表节点结构体
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// 遍历链表并输出每个节点的值
void printList(ListNode* head) {
ListNode* cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
// 创建链表
ListNode* head = new ListNode(1);
ListNode* node1 = new ListNode(2);
ListNode* node2 = new ListNode(3);
head->next = node1;
node1->next = node2;
// 遍历链表并输出每个节点的值
printList(head);
return 0;
}
```
该例子中,我们定义了一个链表节点结构体`ListNode`,其中包含一个整型变量`val`和一个指向下一个节点的指针`next`。我们还定义了一个`printList`函数,用于遍历链表并输出每个节点的值。在`main`函数中,我们创建了一个包含三个节点的链表,并调用`printList`函数输出每个节点的值。