【发布时间】:2019-03-20 11:23:33
【问题描述】:
我有两个链表Target 和List
struct node
{
int data;
struct node *next;
};
struct snode
{
struct node *head;
struct node *last;
int size;
};
void *createlist(struct snode *list)
{
list->head = NULL;
list->last = NULL;
list->size = 0;
}
struct node *createnode(int data)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
return temp;
}
int Add(struct snode *list, int data, int pos)
{
struct node *temp = createnode(data);
if (pos == 0) // add to first node
{
if (list->head == NULL)
{
list->head = temp;
list->last = temp;
}
else
{
temp->next = list->head;
list->head = temp;
}
}
else if (pos == -1) // add to last node
{
if (list->head == NULL)
list->head = temp;
else
{
struct node *pre = list->head;
while (pre->next != NULL)
pre = pre->next;
pre->next = temp;
temp->next = NULL;
}
}
else // add to the middle
{
int k = 1;
struct node *pre = list->head;
while ((pre != NULL) && (k != pos))
{
pre = pre->next;
k++;
}
if ((k != pos) || (pos > list->size))
return 0;
else
{
temp->next = pre->next;
pre->next = temp;
}
}
list->size++;
return 1;;
}
int copy(struct snode *target, struct snode *list)
{
struct node *temp1 = list->head;
struct node *temp2 = createnode(temp1->data);
target->head = temp2;
if (temp1 == NULL)
return 0;
while (temp1 != NULL)
{
temp2->next = temp1->next;
temp1 = temp1->next;
temp2 = temp2->next;
target->size++;
}
return 1;
}
void printlist(struct snode list)
{
while (list.head != NULL)
{
printf("%2d", list.head->data);
list.head = list.head->next;
}
}
int main()
{
struct snode list;
struct snode target;
createlist(&list);
createlist(&target); //create empty linkedlist
Add(&list, 4, 0); //add node to linkedlist
Add(&list, 6, 1);
Add(&list, 9, -1);
Add(&list, 7, 2);
Add(&list, 5, 3);
copy(&target,&list); //copy list to target
combine(&target,&list);
printlist(target);
}
我想连接Target 和List 所以我使用了这个功能
void combine(struct snode *target, struct snode *list)
{
struct node *temp1=list->head;
struct node *temp2=target->head;
while(temp2->next!=NULL)
temp2=temp2->next;
temp2->next = list->head;
}
但是当我打印它时,它会创建无限循环。我尝试调试,我在这一行之后看到了:
temp2->next = list->head
List 的最后一个节点指向List 的第一个节点。
我不知道为什么会这样,谁能告诉我为什么以及如何解决这个问题?
【问题讨论】:
-
您能否添加足够的
main和测试数据来创建minimal reproducible example? -
你还需要在最后加上
target->last= list->last; -
我们还需要查看createlist和Add来了解你构建的链接列表是否OK。
-
发布完整代码。
-
对不起,我刚刚编辑了它。
标签: c linked-list