如何在单链表的最后一个结点再申请一个结点并赋int类型数据C++语言
时间: 2023-05-27 11:01:15 浏览: 44
假设单链表的结点定义如下:
```c
struct Node {
int data;
struct Node* next;
};
```
则在单链表最后一个结点后面添加一个新结点并赋值可以按照以下步骤实现:
1. 新建一个结点并申请内存空间。
2. 将新结点的 `data` 成员赋值为需要添加的整数值。
3. 将新结点的 `next` 成员指向 NULL,表示它是新的最后一个结点。
4. 在遍历单链表时,找到当前最后一个结点的指针(即其 `next` 成员为 NULL 的结点)。
5. 将该结点的 `next` 指向新的结点。
完整的代码实现如下:
```c
struct Node* add_end(struct Node* head, int value) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // 新建结点
new_node->data = value; // 赋值
new_node->next = NULL;
if (head == NULL) { // 链表为空
head = new_node;
} else {
struct Node* cur = head;
while (cur->next != NULL) { // 找到最后一个结点
cur = cur->next;
}
cur->next = new_node; // 将新结点添加到最后
}
return head;
}
```