c语言代码,输入n个字符利用尾插法建立单链表,功能为打印输出该单链表,输出单链表长度,按值查找,插入元素
时间: 2023-04-06 08:04:01 浏览: 163
尾插法单链表的建立
我可以回答这个问题。以下是C语言代码实现尾插法建立单链表,并实现打印输出该单链表、输出单链表长度、按值查找、插入元素的功能:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
typedef struct Node {
char data;
struct Node *next;
} Node;
// 尾插法建立单链表
Node *createList() {
Node *head = NULL, *tail = NULL;
char ch;
printf("请输入n个字符,以空格或回车分隔:\n");
while ((ch = getchar()) != '\n') {
Node *node = (Node *)malloc(sizeof(Node));
node->data = ch;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 打印输出单链表
void printList(Node *head) {
printf("单链表内容为:");
while (head != NULL) {
printf("%c ", head->data);
head = head->next;
}
printf("\n");
}
// 输出单链表长度
int getLength(Node *head) {
int length = 0;
while (head != NULL) {
length++;
head = head->next;
}
return length;
}
// 按值查找
Node *search(Node *head, char value) {
while (head != NULL) {
if (head->data == value) {
return head;
}
head = head->next;
}
return NULL;
}
// 插入元素
void insert(Node **head, char value) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = value;
node->next = NULL;
if (*head == NULL) {
*head = node;
} else {
Node *tail = *head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = node;
}
}
int main() {
Node *head = createList();
printList(head);
printf("单链表长度为:%d\n", getLength(head));
char value;
printf("请输入要查找的字符:");
scanf("%c", &value);
Node *node = search(head, value);
if (node == NULL) {
printf("未找到该字符\n");
} else {
printf("已找到该字符\n");
}
printf("请输入要插入的字符:");
scanf(" %c", &value);
insert(&head, value);
printList(head);
return 0;
}
```
阅读全文