输入3 4 5 6 7 9999一串整数,9999代表结束,通过头插法新建链表,并输出,通过尾插法新建链表并输出。C++代码实现
时间: 2024-10-22 17:16:21 浏览: 55
在C++中,我们可以分别使用头插法(Linked List with Head Insertion)和尾插法(Linked List with Tail Insertion)来处理这个需求。这里是一个简单的示例代码:
首先,我们需要定义一个节点结构(Node)以及单链表的头指针(LinkedList)。
```cpp
#include <iostream>
using namespace std;
// 定义链表节点
struct Node {
int data;
Node* next;
};
// 创建链表头结点
Node* createList(int arr[], int n) {
if (n == 0)
return NULL;
// 创建第一个节点并将数据存储其中
Node* head = new Node();
head->data = arr[0];
head->next = NULL;
// 使用头插法将剩余元素插入链表
for (int i = 1; i < n && arr[i] != 9999; ++i) {
Node* newNode = new Node();
newNode->data = arr[i];
newNode->next = head;
head = newNode;
}
return head;
}
// 尾插法创建链表
void tailInsert(Node** head, int arr[], int n) {
if (*head == NULL || arr[n - 1] == 9999)
return;
Node* last = *head;
for (int i = 0; i < n - 1 && arr[i] != 9999; ++i)
last = last->next;
last->next = new Node();
last->next->data = arr[n - 1];
}
// 打印链表
void printList(Node* head) {
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
int main() {
int arr[] = {3, 4, 5, 6, 7, 9999};
int n = sizeof(arr) / sizeof(arr[0]);
Node* headWithHeadInsertion = createList(arr, n);
cout << "链表(头插法):";
printList(headWithHeadInsertion);
tailInsert(&headWithHeadInsertion, arr, n); // 将链表转换为尾插法
cout << "链表(尾插法):";
printList(headWithHeadInsertion);
return 0;
}
```
在这个代码中,我们首先使用`createList`函数创建一个由输入数组组成、以9999结尾的链表,然后通过`tailInsert`函数将链表改为尾插形式。最后,`printList`函数用于打印链表的内容。运行这个程序会输出两个链表的结果。注意,在实际应用中,`main()`中的`headWithHeadInsertion`在调用`tailInsert`之后已经不再是原始的头插链表,而是经过转换后的尾插链表。
阅读全文
相关推荐


















