【发布时间】:2014-02-09 20:15:11
【问题描述】:
我正在用 C 做一个练习,我必须找出两个列表之间是否存在连接(指向同一节点的指针)。
我正在尝试使用两个for 循环并比较指针(或者我认为是...):
-
newList():创建一个简单的连接列表。 -
findsize():返回节点数。 -
synthesi():打印以控制公共节点的位置,如果存在则返回该节点的指针。
此外,编译器“抱怨”tmp = tmp->next,偶尔也抱怨cur = cur->next,因为list 的最后一个next 指针为空(因为它应该在一个简单的列表中)。
struct list{
int num;
struct list *next;
};
struct list* synthesi(struct list*, struct list*);
int findSize(struct list*);
struct list* newList();
void main()
{
struct list *hd1, *hd2, *syn;
int sizeofhd1, sizeofhd2;
hd1 = newList();
hd2 = newList();
/*do{ test
printf("list1: %d\n", hd1->num);
printf("list1: %d\n", hd2->num);
hd1 = hd1->next;
hd2 = hd2->next;
} while (hd2!=NULL);
*/
sizeofhd1 = findSize(hd1);
sizeofhd2 = findSize(hd2);
//printf("list1: %d\n", sizeofhd1); test
//printf("list2: %d\n", sizeofhd2);
syn = (struct list*)malloc(sizeof(struct list));
syn = synthesi(hd1, hd2);
printf("synthesi: %d\n", syn->num);
}
int findSize(struct list *head)
{
struct list *cur;
int flag = 0;
cur = (struct list*)malloc(sizeof(struct list));
cur = head;
do
{
flag++;
cur = cur->next;
}while (cur!=NULL);
free(cur);
return flag;
}
struct list* synthesi(struct list *head1, struct list *head2)
{
int i,j, pos, sizeofhd1, sizeofhd2;
struct list *tmp;
tmp = (struct list*)malloc(sizeof(struct list));
sizeofhd1=findSize(head1);
sizeofhd2 = findSize(head1);
for (i = 0; i < sizeofhd1; i++)
{
for (j = 0; j < sizeofhd2; j++)
{
if (head1->next == tmp)
{
pos = i + i;
break;
}
tmp = tmp->next;
}
head1 = head1->next;
tmp = head2;
}
if (pos == 0)
{
puts("no connection!\n");
return (struct list*)NULL;
}
else{
puts("found at position: ");
printf("%d\n", pos);
return head1->next;
}
}
struct list* newList()
{
struct list *mylist, *hd;
int i;
hd = (struct list*)malloc(sizeof(struct list));
mylist = (struct list*)malloc(sizeof(struct list));
mylist->num = 7;
mylist->next = (struct list*)malloc(sizeof(struct list));
hd = mylist;
for (i = 0; i < 10; i++)
{
mylist->next = (struct list*)malloc(sizeof(struct list));
mylist->next->num = i + 1;
mylist = mylist->next;
mylist->next = (struct list*)NULL;
}
return hd;
}
【问题讨论】:
-
伙计们,你能请停止用c++标记明显是C的东西吗?提前致谢。
-
您的
list结构实际上不是列表,而是列表中的一个节点。我会将其重命名为node并创建一个带有变量head和cur的list结构并从那里获取它。 -
如果too列表有一个公共节点,所有下一个节点也在两个列表中吗?是不是。