1.4 编写程序,输入若干正整数,按从小到大次序建立1个带头结点单链表,设计一个实现单链表分离算法的Split函数,将原单链表中值为偶数的结点分离出来形成一个新单链表,新单链表中头结点重新申请,其余结点来自原链
时间: 2024-03-11 15:02:38 浏览: 196
有头结点的单链表表的实现
表。以下是我为您编写的C++代码实现:
```c++
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct Node {
int data;
Node* next;
};
// 从小到大插入节点
void insertNode(Node* &head, int val) {
Node* newNode = new Node;
newNode->data = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
return;
}
if (val < head->data) {
newNode->next = head;
head = newNode;
return;
}
Node* p = head;
while (p->next != NULL && p->next->data < val) {
p = p->next;
}
newNode->next = p->next;
p->next = newNode;
}
// 分离偶数节点
Node* split(Node* &head) {
Node* evenHead = new Node;
evenHead->next = NULL;
Node* p = head;
Node* evenP = evenHead;
while (p != NULL) {
if (p->data % 2 == 0) {
evenP->next = p;
evenP = evenP->next;
p = p->next;
evenP->next = NULL;
} else {
p = p->next;
}
}
return evenHead;
}
// 打印链表
void printList(Node* head) {
Node* p = head;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main() {
Node* head = NULL;
int n, val;
cout << "请输入正整数的个数: ";
cin >> n;
cout << "请输入正整数: ";
for (int i = 0; i < n; i++) {
cin >> val;
insertNode(head, val);
}
cout << "原链表为: ";
printList(head);
Node* evenHead = split(head);
cout << "分离出来的偶数节点链表为: ";
printList(evenHead->next);
cout << "原链表剩余的奇数节点为: ";
printList(head);
return 0;
}
```
以上代码实现了从小到大建立单链表和分离偶数节点的功能,并对结果进行了打印输出。注意,分离出来的偶数节点链表的头结点需要重新申请。
阅读全文