c语言输入序号打印某个节点的内容
时间: 2024-05-04 15:16:55 浏览: 18
假设你有一个链表,每个节点包含一个整数和一个指向下一个节点的指针,你可以使用以下代码输入序号并打印相应节点的内容:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
typedef struct Node {
int data;
struct Node* next;
} Node;
// 初始化链表
Node* initList(int n) {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
Node* p = head;
for (int i = 1; i <= n; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
p->next = node;
p = node;
}
return head;
}
// 打印链表
void printList(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 根据序号打印节点内容
void printNode(Node* head, int index) {
Node* p = head->next;
int i = 1;
while (p != NULL && i < index) {
p = p->next;
i++;
}
if (p == NULL) {
printf("序号超出范围!\n");
} else {
printf("节点内容为:%d\n", p->data);
}
}
int main() {
int n = 5;
Node* head = initList(n);
printList(head);
int index;
printf("请输入要打印的节点序号:");
scanf("%d", &index);
printNode(head, index);
return 0;
}
```
在上面的代码中,我们首先定义了一个`Node`结构体表示链表节点,包括一个`int`类型的`data`成员和一个指向下一个节点的指针`next`。然后定义了`initList`函数用于初始化链表,`printList`函数用于打印链表,`printNode`函数用于根据序号打印节点内容。在`main`函数中,我们初始化一个包含5个节点的链表,并打印出来。然后输入要打印的节点序号,调用`printNode`函数打印对应节点的内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)