C:将不同的单词保存到链表中

时间:2012-06-27 13:16:37

标签: c copy linked-list unique distinct

  

可能重复:
  Save distinct words into linked list

我正在尝试编写一个代码,用于读取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
        }

    }

我的第一个清单:您好我的名字是超人

我的第二个清单:你好我的名字< - 仍然是

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

1 个答案:

答案 0 :(得分: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);
    }