2. 遍历单链表,输出所有奇数序号结点数据(头节点后节点为第一个结点,即输出第1,3,5,7…节点),数据间用空格隔开。
时间: 2024-03-13 22:43:38 浏览: 25
假设单链表的结构体定义如下:
```
struct Node {
int data;
struct Node *next;
};
```
遍历单链表,输出所有奇数序号结点数据的代码如下:
```
void printOddNodes(struct Node *head) {
struct Node *current = head->next;
int count = 1;
while (current != NULL) {
if (count % 2 != 0) {
printf("%d ", current->data);
}
current = current->next;
count++;
}
}
```
其中,`head` 是链表头结点,`current` 是当前遍历到的结点,`count` 记录当前结点的序号。遍历单链表时,如果当前结点的序号为奇数,则输出该结点的数据。最后,输出的数据之间用空格隔开。
相关问题
2.遍历单链表,输出所有奇数序号结点数据(头节点后节点为第一个结点,即输出第1,3,5,7…节点),数据间用空格隔开。 函数代码:
以下是遍历单链表输出所有奇数序号结点数据的函数代码:
```c
void printOddNodes(Node *head) {
Node *current = head->next;
int count = 1;
while (current != NULL) {
if (count % 2 != 0) {
printf("%d ", current->data);
}
count++;
current = current->next;
}
}
```
解释:
首先将指针 `current` 指向链表的第一个结点,即头节点的下一个结点。然后使用计数器 `count` 记录当前结点的序号,初始值为1。
接下来,进入循环,当 `current` 指向的结点不为空时,判断当前结点的序号是否为奇数。如果是奇数,则输出当前结点的数据。
最后,将计数器 `count` 加1,并将指针 `current` 指向下一个结点,继续循环,直到遍历完整个链表。
创建单链表并2. 遍历单链表,输出所有奇数序号结点数据(头节点后节点为第一个结点,即输出第1,3,5,7…节点),数据间用空格隔开。 函数代码:
以下是创建单链表并遍历输出所有奇数序号结点数据的代码实现:
```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` 函数遍历单链表,输出所有奇数序号结点的数据。注意,这里的头节点是没有数据的,实际上单链表的第一个节点是头节点的下一个节点。