我正在C中練習,在那裏我必須找出兩個列表(指針在同一節點)之間是否存在連接。c:找到兩個簡單列表之間的連接(公共節點)
我想有兩個for
循環來做到這一點,比較指針(或我是這麼認爲的......):
newList()
:創建一個簡單的連接列表。findsize()
:返回節點數量。synthesi()
:打印控制公共節點的位置並返回節點上的指針(如果存在)。
而且編譯器「抱怨」關於tmp = tmp->next
偶爾因爲最後next
指針list
這爲空(因爲它應該是一個簡單的列表)的約cur = cur->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的東西?提前致謝。 – Griwes
你的'list'結構實際上不是一個列表,而是一個列表中的一個節點。我會將它重命名爲'node',並用變量'head'和'cur'創建一個'list'結構體並從那裏取出。 –
如果太多的列表有一個共同的節點,所有的下一個節點都在這兩個列表?不是嗎。 – Marian