在这个代码的基础上进行修改,遍历单链表,输出所有技术序号的节点数据,并且将数据之间用空格隔开
时间: 2024-03-13 12:44:03 浏览: 16
好的,我可以帮你进行修改。以下是修改后的代码示例:
```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 printListByIndex(ListNode* head) {
int index;
printf("请输入要输出的节点技术序号,以-1结束:");
scanf("%d", &index);
while (index != -1) {
ListNode* p = head->next;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
if (p != NULL) {
printf("%d ", p->data);
}
scanf("%d", &index);
}
printf("\n");
}
// 测试代码
int main() {
ListNode* head = createList();
printf("创建的单链表为:");
printList(head);
printListByIndex(head);
return 0;
}
```
在原有代码的基础上,新增了一个函数`printListByIndex`,用于遍历单链表,输出所有技术序号的节点数据。具体实现是通过输入技术序号,遍历单链表,找到对应节点并输出其数据。连续输入多个技术序号,直到输入-1为止。