C语言单链表输入字符并输出
时间: 2023-07-11 16:09:00 浏览: 55
以下是一个简单的C语言单链表程序,实现了输入字符并输出的功能。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
char data;
struct Node* next;
}Node;
void printList(Node* head){
Node* cur = head;
while(cur != NULL){
printf("%c ", cur->data);
cur = cur->next;
}
printf("\n");
}
int main(){
char c;
Node* head = NULL;
Node* tail = NULL;
while((c = getchar()) != '\n'){
Node* node = (Node*)malloc(sizeof(Node));
node->data = c;
node->next = NULL;
if(head == NULL){
head = node;
tail = node;
}else{
tail->next = node;
tail = node;
}
}
printList(head);
return 0;
}
```
该程序中定义了一个 `Node` 结构体,包含一个数据域 `data` 和一个指向下一个节点的指针 `next`。`printList` 函数用于输出链表中所有节点的数据。
在 `main` 函数中,首先定义了一个头节点 `head` 和尾节点 `tail`,并初始化为 `NULL`。然后通过循环读取用户输入的字符,创建一个新节点并将字符存储到 `data` 中,然后将新节点插入到链表的末尾。
最后调用 `printList` 函数输出链表中的所有节点数据。