#include <stdio.h>
#include <stdlib.h>
// 定义链串的节点
typedef struct Node {
char data; // 节点存储的字符
struct Node* next; // 指向下一个节点的指针
} Node;
// 定义链串的结构体
typedef struct {
Node* head; // 指向链串第一个节点的指针
int length; // 链串的长度
} LinkString;
// 创建一个新的链串节点
Node* createNode(char data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 初始化链串
void initLinkString(LinkString* ls) {
ls->head = NULL;
ls->length = 0;
}
// 在链串末尾添加字符
void appendChar(LinkString* ls, char c) {
Node* newNode = createNode(c);
if (ls->head == NULL) {
ls->head = newNode;
} else {
Node* temp = ls->head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
ls->length++;
}
// 打印链串
void printLinkString(LinkString* ls) {
Node* temp = ls->head;
while (temp != NULL) {
printf("%c", temp->data);
temp = temp->next;
}
printf("\n");
}
// 释放链串占用的内存
void freeLinkString(LinkString* ls) {
Node* temp;
while (ls->head != NULL) {
temp = ls->head;
ls->head = ls->head->next;
free(temp);
}
ls->length = 0;
}
int main() {
LinkString ls;
initLinkString(&ls);
// 向链串中添加字符
appendChar(&ls, 'H');
appendChar(&ls, 'e');
appendChar(&ls, 'l');
appendChar(&ls, 'l');
appendChar(&ls, 'o');
// 打印链串
printLinkString(&ls);
// 释放链串占用的内存
freeLinkString(&ls);
return 0;
}
2.可输入字符串的链串
#define MAX_SIZE 50
typedef struct Node
{
char data[MAX_SIZE + 1];
struct Node* next;
}Node;
//申请空间
Node* createNode(const char* str)
{
Node* newnode = (Node*)malloc(sizeof(Node));
if (newnode == NULL)
{
perror("error");
exit(1);
}
strncpy(newnode->data, str, MAX_SIZE);
newnode->data[MAX_SIZE] = '\0';
newnode->next = NULL;
return newnode;
}
//尾插
void Nodepush(Node** head,const char* str)
{
Node* newnode = createNode(str);
if (newnode == NULL)
{
perror("error");
exit(1);
}
if (*head == NULL)
{
*head = newnode;
}
else
{
Node* ret = *head;
while (ret->next != NULL)
{
ret = ret->next;
}
ret->next = newnode;
}
}
//打印
void printNode(Node** head)
{
Node* ret = *head;
while (ret)
{
printf("%s->", ret->data);
ret = ret->next;
}
printf("NULL\n");
}
//释放
void freeNode(Node** head)
{
Node* ret = *head;
while (ret)
{
Node* count = ret->next;
free(ret);
ret = count;
}
}
int main()
{
Node* head = NULL;
Nodepush(&head, "FanJunXi");
Nodepush(&head, "Love");
Nodepush(&head, "JJ_Lin");
printNode(&head);
freeNode(&head);
}