C, Print Linked List of Strings

落爺英雄遲暮 提交于 2019-12-05 02:25:59

问题


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.

Short: How to I print a linked list?


回答1:


There are no stupid questions1. Here's some pseudo-code to get you started:

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.


1 Well, actually, there probably are, but this isn't one of them :-)




回答2:


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;
}



回答3:


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)
}



回答4:


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.

You do this until the next address is NULL (which means you've reached your tail).



来源:https://stackoverflow.com/questions/4372976/c-print-linked-list-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!