c++写一个单链表 分离字符串中的单词
时间: 2024-05-24 07:12:32 浏览: 101
用C++实现一个单链表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
typedef struct node {
char word[MAX_LEN];
struct node *next;
} Node, *LinkedList;
LinkedList createLinkedList(char *str);
void printLinkedList(LinkedList L);
void freeLinkedList(LinkedList L);
int main() {
char str[MAX_LEN];
printf("Please input a string: ");
fgets(str, MAX_LEN, stdin);
str[strlen(str)-1] = '\0'; // 去掉输入字符串的换行符
LinkedList L = createLinkedList(str);
printLinkedList(L);
freeLinkedList(L);
return 0;
}
// 创建单链表
LinkedList createLinkedList(char *str) {
LinkedList L = (LinkedList)malloc(sizeof(Node));
L->next = NULL;
Node *p = L;
char *token = strtok(str, " ");
while (token != NULL) {
Node *newNode = (Node *)malloc(sizeof(Node));
strcpy(newNode->word, token);
newNode->next = NULL;
p->next = newNode;
p = newNode;
token = strtok(NULL, " ");
}
return L;
}
// 打印单链表
void printLinkedList(LinkedList L) {
Node *p = L->next;
while (p != NULL) {
printf("%s ", p->word);
p = p->next;
}
printf("\n");
}
// 释放单链表
void freeLinkedList(LinkedList L) {
Node *p = L;
while (p != NULL) {
Node *tmp = p;
p = p->next;
free(tmp);
}
}
阅读全文