创建单链表并2. 遍历单链表,输出所有奇数序号结点数据(头节点后节点为第一个结点,即输出第1,3,5,7…节点),数据间用空格隔开。 函数代码:
时间: 2024-03-13 12:44:54 浏览: 24
以下是创建单链表并遍历输出所有奇数序号结点数据的代码实现:
```c++
#include <iostream>
using namespace std;
// 单链表节点结构体
struct Node {
int data;
Node* next;
Node(int d) : data(d), next(nullptr) {}
};
// 创建单链表
Node* createLinkedList() {
int n;
cout << "请输入链表节点个数:";
cin >> n;
Node* head = new Node(-1);
Node* curr = head;
for(int i = 0; i < n; i++) {
int data;
cout << "请输入第" << i+1 << "个节点的数据:";
cin >> data;
Node* node = new Node(data);
curr->next = node;
curr = node;
}
return head;
}
// 遍历单链表,输出所有奇数序号结点数据
void printOddNodes(Node* head) {
Node* curr = head->next;
int count = 1;
while (curr != nullptr) {
if (count % 2 == 1) {
cout << curr->data << " ";
}
curr = curr->next;
count++;
}
}
int main() {
// 创建单链表
Node* head = createLinkedList();
// 遍历单链表,输出所有奇数序号结点数据
cout << "所有奇数序号结点数据为:";
printOddNodes(head);
cout << endl;
return 0;
}
```
该程序首先通过 `createLinkedList` 函数创建单链表,然后调用 `printOddNodes` 函数遍历单链表,输出所有奇数序号结点的数据。注意,这里的头节点是没有数据的,实际上单链表的第一个节点是头节点的下一个节点。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)