分别用头插法和尾插法创建并输出带附加头结点的单链表。 头插法是指每个新元素都插入到链表的最前面,即头结点和链表第一个元素之间; 尾插法指的是每个新元素都插入到链表的最后面。算法实现
时间: 2024-05-08 08:20:11 浏览: 16
好的,我已经明白您的问题了。下面是使用头插法和尾插法创建并输出带附加头结点的单链表的算法实现:
使用头插法创建并输出带附加头结点的单链表算法实现:
```
#include <iostream>
using namespace std;
// 定义链表结点
struct ListNode {
int value;
ListNode* next;
ListNode(int x) : value(x), next(nullptr) {}
};
// 头插法创建链表
ListNode* createListByHeadInsert() {
ListNode* head = new ListNode(-1);
int num = 0;
cout << "请输入元素个数:";
cin >> num;
cout << "请输入元素值:";
for (int i = 0; i < num; ++i) {
int val = 0;
cin >> val;
ListNode* node = new ListNode(val);
node->next = head->next;
head->next = node;
}
return head;
}
// 输出链表
void printList(ListNode* head) {
ListNode* cur = head->next;
while (cur != nullptr) {
cout << cur->value << " ";
cur = cur->next;
}
cout << endl;
}
// 测试
int main() {
ListNode* head = createListByHeadInsert();
cout << "头插法创建的链表为:";
printList(head);
return 0;
}
```
使用尾插法创建并输出带附加头结点的单链表算法实现:
```
#include <iostream>
using namespace std;
// 定义链表结点
struct ListNode {
int value;
ListNode* next;
ListNode(int x) : value(x), next(nullptr) {}
};
// 尾插法创建链表
ListNode* createListByTailInsert() {
ListNode* head = new ListNode(-1);
ListNode* tail = head;
int num = 0;
cout << "请输入元素个数:";
cin >> num;
cout << "请输入元素值:";
for (int i = 0; i < num; ++i) {
int val = 0;
cin >> val;
ListNode* node = new ListNode(val);
tail->next = node;
tail = tail->next;
}
return head;
}
// 输出链表
void printList(ListNode* head) {
ListNode* cur = head->next;
while (cur != nullptr) {
cout << cur->value << " ";
cur = cur->next;
}
cout << endl;
}
// 测试
int main() {
ListNode* head = createListByTailInsert();
cout << "尾插法创建的链表为:";
printList(head);
return 0;
}
```
希望这些代码对您有所帮助。如果您想了解更多关于链表的算法实现,可以参考CSDN上关于数据结构和算法的博客。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)