Save distinct words into linked list

爷,独闯天下 提交于 2019-12-01 14:49:36

These three lines is one likely culprit:

if(ori == NULL && copy == NULL) { //first time.
    ori = ori->next;
    copy = copy->next;

Here you check if ori and copy are NULL, then you immediately dereference those NULL pointers!

In your code, distinct is not the name of a variable but of a structure. You seem to have misunderstood pointers, hopefully this will help although it is not directly related to your question.

I've left out a lot of error checking to make the code look simpler.

typedef struct listnode {
    char string[50];
    struct listnode *next;
} list_node;

typedef struct listbase {
    list_node *head;
    int numberOfElements;
} list;

/* Add a new string at the start of the list
*/
void ListPrepend(list *myList, char *myString) {
    list_node *newNode = malloc(sizeof *newNode); /* create node to store string */

    strcpy(newNode->string, myString); /* copy string into node */
    newNode->next = myList->head;      /* New node now followed by whole list */
    myList->head = newNode;            /* List now starts with new node */
    myList->numberOfElements++;
}

/* Add a new string at the end of the list
*/
void ListAppend(list *myList, char *myString) {
    list_node *newNode = malloc(sizeof *newNode), /* create node to store string */
              *currentNode = myList->head; /* pointer to node so we can find the end */

    strcpy(newNode->string, myString); /* copy string into new node */
    newNode->next = NULL;              /* Nothing following this node */

    if ( myList->head == NULL ) {
        myList->head = newNode; /* we didn't have a start node so assign it */
    } else {
        /* if there is a next node, move to it */
        while ( currentNode->next != NULL ) {
            currentNode = currentNode->next;
        }
        /* there is no next node so add new node on the end */
        currentNode->next = newNode;
    }
    myList->numberOfElements++;
}

/* Show the list in order head to tail
*/
void ListDisplay(list *myList) {
    list_node *currentNode = myList->head;

    while ( currentNode != NULL ) {
        printf("%s\n", currentNode->string);
        currentNode = currentNode->next;
    }
}

int main() {
    list distinct = {0}; /* Now there is a variable called distinct */
    char name[][20] = {"Lim Zheng Yue", "Monkey", "Dave"};

    ListAppend(&distinct, name[0]);
    ListAppend(&distinct, name[1]);
    ListPrepend(&distinct, name[2]);
    ListDisplay(&distinct);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!