-2

可能重复:
将不同的单词保存到链表中

我正在尝试编写一个从 1 个链表中读取单词的代码。

然后确定不同/唯一的单词,并将这些单词保存到另一个链表中。

不幸的是代码不起作用,需要帮助来解决这个问题。

这是我到目前为止所得到的,我已经添加了评论希望它有所帮助。

struct list {

    char string[50];
    struct list *next;
};

list *header;
list *next = NULL;


struct distinct {

    char string[50];
    struct distinct *dnext; 
};

distinct *track;
distinct *dnext;


void checkdistinct() {

        int dwcheck = 0;  //as boolean to check whether distinct word is found
        list *ori;        //first struct
        ori = header->next;
        distinct *copy;   //second struct
        distinct *check = NULL;

        track = (distinct*)malloc(sizeof(distinct));
        track->dnext=NULL;
        copy = track;

        if(copy == track) {   // direct copy first time
            strcpy(copy->string, ori->string);
        }
        else {}

        while(ori->next!=NULL) { // while original struct did not end
            check = track;      

            while(check->dnext != NULL) { //check end when second list ends
                    if(strcmp(ori->string, check->string)!=0) {
                        check = check->dnext;
                    }
                    else if(strcmp(ori->string, check->string)==0) {
                        dwcheck = 1;
                        ori = ori->next; // original list will move one node next
                        check = check->dnext; // check pointer continues
                    }
            }

            copy->dnext = (distinct*)malloc(sizeof(distinct)); // new node for new word
            copy = copy->dnext;

            if(dwcheck != 1) { // when boolean = false, original will move one node next, next word will be copied
                ori = ori->next;   // as the node is moved one node (above) when boolean = true
            }
            else if(dwcheck == 1) {
                strcpy(copy->string, ori->string);
            }

            dwcheck = 0; // reset
            copy->dnext=NULL; // set not copied node as NULL each time
            check = NULL; // reset
        }

    }

我的第一个清单:你好我的名字叫超人

我的第二个列表:你好,我的名字 <-- 仍然是

抱歉编码不好,仍然是新手。谢谢!

4

1 回答 1

0

我认为最好先对原始列表进行排序。然后你可以这样做:

prev = 0; current = first string;

while (current) {
  if (strcmp(prev, current)!=0) {
     add current to distinct list;
  } 
  prev = current;
  current = current->next;
}

这部分对我来说也没有意义,因为它永远都是真的:

    copy = track;

    if(copy == track) {   // direct copy first time
        strcpy(copy->string, ori->string);
    }
于 2012-06-27T13:22:58.667 回答