输入n个单词,建立单链表,然后从头节开始遍历输出开始输出
时间: 2024-03-20 15:43:28 浏览: 14
好的,这是一个简单的链表问题。你可以按照以下步骤来解决它:
1. 定义一个结构体来表示链表节点:
```
struct ListNode {
char* word; // 存储单词
ListNode* next; // 下一个节点指针
};
```
2. 定义一个函数来创建节点并将它们链接起来:
```
ListNode* createLinkedList(char** words, int n) {
ListNode* head = NULL;
ListNode* tail = NULL;
for (int i = 0; i < n; i++) {
ListNode* node = new ListNode;
node->word = words[i];
node->next = NULL;
if (tail == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
```
3. 定义一个函数来遍历输出链表中的所有单词:
```
void traverseLinkedList(ListNode* head) {
ListNode* p = head;
while (p != NULL) {
printf("%s ", p->word);
p = p->next;
}
}
```
4. 在主函数中调用这些函数:
```
int main() {
char* words[] = {"hello", "world", "this", "is", "a", "test"};
int n = 6;
ListNode* head = createLinkedList(words, n);
traverseLinkedList(head);
return 0;
}
```
这样就可以遍历输出链表中的所有单词了。注意,在实际使用中,需要释放链表中的内存,以避免内存泄漏。