【问题标题】:C: Save distinct words into linked list [duplicate]C:将不同的单词保存到链表中[重复]
【发布时间】:2012-06-27 13:16:37
【问题描述】:

可能重复:
Save distinct words into linked list

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

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

不幸的是,代码无法正常工作,需要帮​​助来解决这个问题。

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

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
        }

    }

我的第一个列表:你好我的名字叫超人

我的第二个列表:你好,我的名字

抱歉编码不好,还是个新手。谢谢!

【问题讨论】:

  • 这是作业吗?因为您通常会为此使用集合(作为 BST,或自平衡树或散列)。
  • 完全重复。包括结构定义隐含 typedef 的假设。
  • 我会使用合并排序,然后删除重复项...
  • 我会使用 refcounted hashtable。

标签: c copy linked-list unique distinct


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2012-02-14
    相关资源
    最近更新 更多