建立一个包含3~5个数据元素的链式存储线性表
时间: 2024-05-10 20:21:04 浏览: 7
假设数据元素的类型为整数,可以建立如下的链式存储线性表:
```
struct Node {
int data;
Node* next;
};
Node* head = NULL;
Node* tail = NULL;
void addElement(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
void printList() {
Node* current = head;
while (current != NULL) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
```
以上代码实现了向链表中添加数据元素和打印链表的功能。可以通过调用 `addElement` 函数向链表中添加数据,然后调用 `printList` 函数打印链表中的所有元素。例如,可以这样使用该链表:
```
addElement(1);
addElement(2);
addElement(3);
printList(); // 输出:1 2 3
```