给我一个创建并显示链表的可成功运行的c++程序
以下是一个创建并显示链表的C++程序:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
void insert(Node*& head, int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void display(Node* head) {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
int main() {
Node* head = NULL;
insert(head, 1);
insert(head, 2);
insert(head, 3);
display(head);
return 0;
}
运行结果为:1 2 3
原文地址: https://www.cveoy.top/t/topic/bhtU 著作权归作者所有。请勿转载和采集!