在这个代码的基础上进行修改,遍历单链表,输出所有奇数序号的节点数据,并且将数据之间用空格隔开
时间: 2024-03-13 12:44:08 浏览: 18
好的,我可以帮你进行修改。以下是修改后的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点类型
typedef struct ListNode {
int data;
struct ListNode* next;
} ListNode;
// 创建带头节点的单链表
ListNode* createList() {
ListNode* head = (ListNode*)malloc(sizeof(ListNode)); // 创建头节点
head->next = NULL; // 头节点的next指针初始化为NULL
int x;
printf("请输入基础整数数据,以-1结束:");
scanf("%d", &x);
while (x != -1) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode)); // 创建新节点
node->data = x; // 新节点的data域赋值
node->next = head->next; // 新节点的next指针指向头节点的下一个节点
head->next = node; // 头节点的next指针指向新节点
scanf("%d", &x);
}
return head;
}
// 遍历单链表,输出所有奇数序号的节点数据
void printListByOddIndex(ListNode* head) {
ListNode* p = head->next;
int index = 1;
while (p != NULL) {
if (index % 2 == 1) {
printf("%d ", p->data);
}
p = p->next;
index++;
}
printf("\n");
}
// 测试代码
int main() {
ListNode* head = createList();
printf("创建的单链表为:");
ListNode* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
printf("所有奇数序号的节点数据为:");
printListByOddIndex(head);
return 0;
}
```
在原有代码的基础上,新增了一个函数`printListByOddIndex`,用于遍历单链表,输出所有奇数序号的节点数据。具体实现是通过遍历单链表,判断节点的技术序号是否为奇数,如果是则输出该节点的数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)