我对链表没有很好的理解,我不知道是否可能,但我需要这样做:)我有一个加载到结构的链表,我需要比较一个结构上的所有字符......最好用一个例子:
这没有链接列表
结构
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");
现在我需要做这样的事情但是使用链表
答案 0 :(得分:1)
首先:int strcmp(const char * str1,const char * str2)比较两个C字符串(char指针)。这意味着a.name [i]应该是一个char指针而不是char!确保是这种情况(即确保a.name是一个c-string数组数组,不一个字符数组)。
其次,如果是前一种情况,您的代码只会将字符串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;
}
或者如果要将所有字符串相互比较,则使用双循环。
答案 1 :(得分: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;
}
但是,要理解这一点,你需要了解指针的基本原理。
答案 2 :(得分: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