编写C++程序,建立两个带头节点的单链表,输入若干整数,将正整数插入第一个单链表,将负整数插入第二个单链表,插入前和插入后单链表保持递增次序,打印这两个单链表,最后销毁。
时间: 2024-06-15 16:06:44 浏览: 7
编写C++程序,建立两个带头节点的单链表,实现将正整数插入第一个单链表,将负整数插入第二个单链表,并保持递增次序。以下是一个示例代码:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 插入节点到链表中并保持递增次序
void insertNode(ListNode* head, int val) {
ListNode* newNode = new ListNode(val);
ListNode* cur = head;
while (cur->next && cur->next->val < val) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
}
// 打印链表
void printList(ListNode* head) {
ListNode* cur = head->next;
while (cur) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
// 销毁链表
void destroyList(ListNode* head) {
ListNode* cur = head;
while (cur) {
ListNode* temp = cur;
cur = cur->next;
delete temp;
}
}
int main() {
// 建立两个带头节点的单链表
ListNode* list1 = new ListNode(0); ListNode* list2 = new ListNode(0);
// 输入若干整数,将正整数插入第一个单链表,将负整数插入第二个单链表
int num;
cout << "请输入整数(输入0结束):" << endl;
cin >> num;
while (num != 0) {
if (num > 0) {
insertNode(list1, num);
} else {
insertNode(list2, num);
}
cin >> num;
}
// 打印两个单链表
cout << "第一个单链表:";
printList(list1); cout << "第二个单链表:";
printList(list2);
// 销毁两个单链表
destroyList(list1);
destroyList(list2);
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)