用链表插入新数据c
时间: 2023-11-08 11:05:33 浏览: 25
在 C++ 中,我们可以使用指针和动态内存分配来实现链表数据结构。下面是一个简单的链表插入新数据的示例代码:
```
struct Node {
int data;
Node* next;
};
void insert(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
int main() {
Node* head = NULL;
// 插入新节点
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
// 遍历链表并输出
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
return 0;
}
```
在这个示例代码中,我们定义了一个 `Node` 结构体,包含一个整型变量 `data` 和一个指向下一个节点的指针 `next`。`insert` 函数接受一个指向头节点指针的指针 `head_ref` 和一个新数据 `new_data`,它会创建一个新的节点,将新数据存储到 `data` 中,将原来的头节点作为它的下一个节点,最后将这个新节点设置为新的头节点。在 `main` 函数中,我们首先将头节点初始化为 `NULL`,然后调用 `insert` 函数三次,插入三个新节点。最后,我们遍历整个链表,并输出每个节点的数据。