题目:下面有结构node的定义,指针head中存放着node节点组成 的单链表的首节点地址,函数odd(head)获取head指向链表 中的序号(注意不是node结构的data字段,且序号从0开始编号) 为奇数的节点,并将这些节点按原有序组成新链表返回。 要求新链表中的节点采用动态内存分配的方式构建, 从而不破坏原链表。如:head指向的链表为:1->2->3->4->5->6, 则odd(head)得到的链表为:2->4->6。请完成函数odd的编写 #include <iostream> #include <fstream> using namespace std; struct node { //链表节点定义 int data; node* next; }; node* odd(node* h) { /**********Program**********/ /********** End **********/ } int main() { int number; int temp; cin >> number; cin >> temp; node* head = NULL, * t, *tmp; head = new node; head->next = NULL; head->data = temp; t = head; for (int i = 1; i< number; i++) { cin >> temp; t->next = new node; t = t -> next; t->data = temp; t->next = NULL; } t = odd(head); tmp = t; cout << tmp->data; tmp = tmp->next; while (tmp) { cout << "->" << tmp->data; tmp = tmp->next; } cout << endl; return 0; }
时间: 2023-08-06 18:07:15 浏览: 108
以下是函数odd的实现代码:
```c++
#include <iostream>
using namespace std;
struct node { //链表节点定义
int data;
node* next;
};
node* odd(node* h) {
node* newHead = NULL; // 新链表的头指针
node* newTail = NULL; // 新链表的尾指针
node* current = h;
int index = 0;
while (current != NULL) {
if (index % 2 != 0) { // 如果序号为奇数
// 创建新节点
node* newNode = new node;
newNode->data = current->data;
newNode->next = NULL;
if (newHead == NULL) { // 如果新链表为空
newHead = newNode;
newTail = newNode;
} else {
newTail->next = newNode;
newTail = newNode;
}
}
current = current->next;
index++;
}
return newHead;
}
int main() {
int number;
int temp;
cin >> number;
cin >> temp;
node* head = NULL, * t, *tmp;
head = new node;
head->next = NULL;
head->data = temp;
t = head;
for (int i = 1; i < number; i++) {
cin >> temp;
t->next = new node;
t = t->next;
t->data = temp;
t->next = NULL;
}
t = odd(head);
tmp = t;
cout << tmp->data;
tmp = tmp->next;
while (tmp) {
cout << "->" << tmp->data;
tmp = tmp->next;
}
cout << endl;
return 0;
}
```
输入示例:
```
6
1 2 3 4 5 6
```
输出示例:
```
2->4->6
```
阅读全文