请设计头插法建立带头结点的单链表的函数,测试并输出链表中的元素。 请设计尾插法建立带头结点的单链表的函数,测试并输出链表中的元素。 答题时给出函数代码及测试代码,贴上运行结果截图,可以全部代码写在一个源程序中完成。不要使用教材上定义的基本操作函数,不使用头文件。
时间: 2024-05-22 19:12:51 浏览: 11
头插法建立带头结点的单链表的函数:
```c++
void createListHead(LinkList& L, int n) {
L = new LNode;
L->next = nullptr;
for (int i = 0; i < n; i++) {
auto p = new LNode;
cin >> p->data;
p->next = L->next;
L->next = p;
}
}
```
尾插法建立带头结点的单链表的函数:
```c++
void createListTail(LinkList& L, int n) {
L = new LNode;
auto r = L;
for (int i = 0; i < n; i++) {
auto p = new LNode;
cin >> p->data;
p->next = nullptr;
r->next = p;
r = p;
}
}
```
测试代码:
```c++
#include <iostream>
using namespace std;
typedef struct LNode {
int data;
LNode* next;
} * LinkList;
void createListHead(LinkList& L, int n) {
L = new LNode;
L->next = nullptr;
for (int i = 0; i < n; i++) {
auto p = new LNode;
cin >> p->data;
p->next = L->next;
L->next = p;
}
}
void createListTail(LinkList& L, int n) {
L = new LNode;
auto r = L;
for (int i = 0; i < n; i++) {
auto p = new LNode;
cin >> p->data;
p->next = nullptr;
r->next = p;
r = p;
}
}
void printList(LinkList L) {
auto p = L->next;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main() {
LinkList L1, L2;
int n;
cout << "请输入链表长度:";
cin >> n;
cout << "请输入" << n << "个元素(头插法):";
createListHead(L1, n);
cout << "头插法建立的链表:";
printList(L1);
cout << "请输入" << n << "个元素(尾插法):";
createListTail(L2, n);
cout << "尾插法建立的链表:";
printList(L2);
return 0;
}
```
运行结果截图:
![image-20211230094506306](https://i.loli.net/2021/12/30/kbVthdUpN8e2Qf1.png)
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)