按之前题目要求补全以下代码/*-------------------------------------------------- 编程要求 函数node* insertBefore(node* head, node* tmp)的功能是将节点tmp插入到其对“偶节”点前面,并返回新链表。 如果不存在对偶节点,则将tmp插入链表头部。所谓的“对偶”节点是指他们的data值的和为0。 说明:链表head中节点的data值各不相同。 ------------------------------------------------*/ #include <iostream> using namespace std; struct node { int data; node* next; }; node* insertBefore(node* head, node* tmp); void output(node* head); int main() { int n; cin >> n; node* head = NULL, * tmp; bool flag; for (int i = 0; i < n; i++) { tmp = new node; cin >> tmp->data; tmp->next = head; head = tmp; } //output(head); // insert a node after its dual number tmp = new node; cin >> tmp->data; head = insertBefore(head, tmp); output(head); } void output(node* head) { while (head) { cout << head->data; head = head->next; if (head) cout << "->"; } cout << endl; }
时间: 2023-08-24 16:30:50 浏览: 99
好的,以下是完整的代码实现:
```c++
#include <iostream>
using namespace std;
struct node {
int data;
node* next;
};
node* insertBefore(node* head, node* tmp);
void output(node* head);
int main() {
int n;
cin >> n;
node* head = NULL, * tmp;
bool flag;
for (int i = 0; i < n; i++) {
tmp = new node;
cin >> tmp->data;
tmp->next = head;
head = tmp;
}
//output(head);
// insert a node after its dual number
tmp = new node;
cin >> tmp->data;
head = insertBefore(head, tmp);
output(head);
}
void output(node* head) {
while (head) {
cout << head->data;
head = head->next;
if (head) cout << "->";
}
cout << endl;
}
node* insertBefore(node* head, node* tmp) {
if (head == nullptr) {
return tmp;
}
node* pre = head;
node* cur = head->next;
int sum = tmp->data + head->data;
while (cur != nullptr && sum != 0) {
sum += cur->data;
pre = cur;
cur = cur->next;
}
if (sum == 0) {
tmp->next = cur;
pre->next = tmp;
} else {
tmp->next = head;
head = tmp;
}
return head;
}
```
阅读全文