0

我对链表不是很了解,我不知道这是否可能,但我需要这样做:) 我有一个加载到结构中的链表,我需要比较所有字符在结构上......最好举个例子:

这是没有链表

结构

typedef struct x{
char name[100];
}x;

typedef x Info;

typdef struct Elem{
Info node;
struct Elem*next;
}Element;


  for(i=0;i<100;i++){
  if(strcmp(a.name[i],a.name[i+1])==0){
  printf("Same name\n");
  }
  }
  else
  printf("Diff name\n");

现在我需要做这样的事情,但使用链表

4

3 回答 3

1

首先: int strcmp ( const char * str1, const char * str2 ) 比较两个 C 字符串(char 指针)。这意味着 a.name[i] 应该是 char 指针而不是 char!确保是这种情况(即确保 a.name 是一个 c 字符串数组,而不是一个字符数组)。

其次,如果是前一种情况,您的代码只会将字符串 i 与字符串 i+1 进行比较。它不会将所有字符串相互比较。

无论如何,看起来你并没有以正确的方式做任何你想做的事情。我猜你想要一个这样定义的结构:

struct example {
    char * name;
    // other members of choice
    example * next;
}

用于启用链表数据类型的名称、其他成员和下一个指针的占位符。这样,您可以将名称与以下内容进行比较:

while (list->next != 0 && list->next->next != 0) {
    if (strcmp(list->name, list->next->name) == 0) // do something;
    else // do something else;
}

或者如果您想将所有字符串相互比较,则使用双循环。

于 2011-06-29T23:36:57.963 回答
0

因此,您需要做的第一件事是了解链表的基础知识。您可以在这里详细阅读:http: //www.codeproject.com/KB/cpp/linked_list.aspx

注意:在您理解指针之前,您真的无法理解链表。http://www.cplusplus.com/doc/tutorial/pointers/

本质上,链表由许多相互链接的“节点”组成。每个节点至少有两条数据,一条是数据(在您的情况下是一个字符),另一条是指向列表中下一个节点的指针。

定义一个结构看起来像(在伪代码中):

LinkedList nodeT {
    char *c; //NOTE: strcmp only compares pointers to chars
    nodeT *nextNode;
}

您将有一个指向链表第一个节点的指针。就像是:

nodeT *firstElement;

然后循环浏览整个列表是小菜一碟:

nodeT *curElement = firstElement;
while(curElement->next != NULL) { //assuming the last node's next pointer is NULL
    if(strcmp(curElement->c,curElement->next->c)==0){
        printf("Same name\n");
    } else {
         printf("Diff name\n");
    }
    curElement = curElement->nextNode;
}

但同样,要理解这一点,您需要了解指针的基础知识。

于 2011-06-29T23:36:43.490 回答
0

这是一个遍历链表并比较相邻元素名称的程序。我冒昧地重命名了一些东西,但是数据结构的代码与您的相同。

#include <string.h>
#include <stdio.h>
#include <assert.h>

typedef struct Info_ {
    char name[100];
} Info;

typedef struct Element_ {
    Info info;
    struct Element_* next;
} Element;

void print_comparisons(Element* elm)
{
    assert(elm);

    Element* cur = elm;
    Element* next = cur->next;
    for (; next; cur = next, next = next->next) {
        if (strcmp(cur->info.name, next->info.name) == 0)
            printf("Same name\n");
        else
            printf("Diff name\n");
    }
}

int main()
{
    Info a; a.name[0] = 'A'; a.name[1] = '\0';
    Info b; b.name[0] = 'B'; b.name[1] = '\0';
    Info c; c.name[0] = 'B'; c.name[1] = '\0';
    Info d; d.name[0] = 'D'; d.name[1] = '\0';
    Element na; na.info = a;
    Element nb; nb.info = b;
    Element nc; nc.info = c;
    Element nd; nd.info = d;

    na.next = &nb;
    nb.next = &nc;
    nc.next = &nd;
    nd.next = NULL;

    print_comparisons(&na);
}

程序的输出:

Diff name
Same name
Diff name
于 2011-06-29T23:51:47.450 回答