开发者

C - String Linked List

I need to take the following code, and modify 开发者_如何学Cit to accept strings as arguments, instead of ints. In the end, I need the program to take all command line arguments, and add them to a linked list of strings.

So if the input was six seven eight, when i printed the linked list, it would print: eight seven six.

#include <stdio.h>
#include <stdlib.h>

typedef struct iNode
{
    int myInt;
    struct iNode* next;
} IntNode, *IntNodePtr;

IntNodePtr insert(int i, IntNodePtr p)
{
    IntNodePtr newp = malloc(sizeof(struct iNode));
    newp->myInt = i;
    newp->next = p;
    return newp;
}

printlist(IntNodePtr p)
{
    if(p == NULL)
        printf("\n");
    else
    {
        printf("%d ", p->myInt);
        printlist(p->next);
    }
}

main(int argc, char* argv[])
{
    int n = 5;

    if(argc > 1)
    n = atoi(argv[1]);

    IntNodePtr iNodeList;
    iNodeList = NULL;
    int i = 0;

    while(i < n)
    {
        iNodeList = insert(i++, iNodeList);
        printf("List is now: ");
        printlist(iNodeList);
    }
}


If printing the solution backwards is the problem, just maintain a global head ptr that points at the first iNode. When you have to print, while(headPtr.next !=null){ printf(...); }


I think your question relates to the order of items in the list.

Consider that, with linked lists, it is possible to add items to the head, to the tail, or insert them at an arbitrary place.

Look at the insert() function, it adds new items where?

Simplistically, you can just reverse the order in which you insert items. In real life that probably won't go down too well.

Maybe maintain a tail pointer? And write an addItemToTail() function?


You should read more about pointers and memory. Good place to learn that is Stanford CS Education Library. You'll find there also nice materials about linked lists.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜