C语言 C、打印字符串链表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4372976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C, Print Linked List of Strings
提问by JC Leyba
I have to write a C program that uses a linked list. I have created a list and added elements to the list. But I don't know how to print all the elements in the list. The list is a list of strings. I figured I'd somehow increment through the list, printing every string that's there, but I can't figure out a way to do this.
我必须编写一个使用链表的 C 程序。我创建了一个列表并将元素添加到列表中。但我不知道如何打印列表中的所有元素。该列表是一个字符串列表。我想我会以某种方式递增列表,打印那里的每个字符串,但我想不出一种方法来做到这一点。
Short: How to I print a linked list?
简短:如何打印linked list?
回答by paxdiablo
There are no stupid questions1. Here's some pseudo-code to get you started:
没有愚蠢的问题1。这里有一些伪代码可以帮助您入门:
def printAll (node):
while node is not null:
print node->payload
node = node->next
printAll (head)
That's it really, just start at the head node, printing out the payload and moving to the next node in the list.
就是这样,只需从头节点开始,打印出有效负载并移动到列表中的下一个节点。
Once that next node is the end of the list, stop.
一旦下一个节点是列表的末尾,停止。
1Well, actually, there probably are,but this isn't one of them :-)
1嗯,实际上,可能有,但这不是其中之一:-)
回答by Hoàng Long
You can use a pointer to iterate through the link list. Pseudo code:
您可以使用指针遍历链接列表。伪代码:
tempPointer = head
while(tempPointer not null) {
print tempPointer->value;
tempPointer = tempPointer->next;
}
回答by Phong
pseudo code:
伪代码:
struct list
{
type value;
struct list* pNext;
}
void function()
{
struct list L;
// .. element to L
// Iterate each node and print
struct list* node = &L;
do
{
print(node->value)
node = node->next;
}
while(node != NULL)
}
回答by alcoholtech
I'm not quite sure if this is what you're looking for, but usually you store in your DS, a pHead (that is a pointer to the first element), and implement a function that retrieves the next address of the string-node.
我不太确定这是否是您要查找的内容,但通常您会在 DS 中存储一个 pHead(即指向第一个元素的指针),并实现一个函数来检索字符串的下一个地址-节点。
You do this until the next address is NULL (which means you've reached your tail).
你这样做直到下一个地址为NULL(这意味着你已经到达你的尾巴)。

