数据结构尾插法单链表
时间: 2023-10-10 14:09:22 浏览: 230
尾插法是单链表中一种常用的插入方法,可以在链表的尾部添加元素。具体步骤如下:
1. 创建一个新节点,将要插入的元素赋值给该节点的数据域。
2. 如果链表为空,将新节点作为头节点。
3. 如果链表不为空,则找到链表的尾节点(即指向NULL的节点),将新节点链接到尾节点的next指针上。
4. 将新节点设置为尾节点。
以下是一个示例代码实现尾插法单链表:
```C++
#include <iostream>
// 定义链表节点
struct Node {
int data;
Node* next;
};
// 尾插法创建单链表
Node* createLinkedList() {
Node* head = nullptr; // 头节点
Node* tail = nullptr; // 尾节点
int num;
std::cout << "请输入链表元素(输入-1表示结束):" << std::endl;
std::cin >> num;
while (num != -1) {
Node* newNode = new Node();
newNode->data = num;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
std::cin >> num;
}
return head;
}
// 打印单链表
void printLinkedList(Node* head) {
Node* p = head;
std::cout << "链表元素为:";
while (p != nullptr) {
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
}
int main() {
Node* head = createLinkedList();
printLinkedList(head);
return 0;
}
```