我试图在C中创建一个链接列表,我似乎无法弄清楚为什么我的光标不会转到下一个节点。我将当前节点设置为下一个节点,但是当我打印出光标地址时,它是相同的。我相信这会导致我无限循环,因为这是我的主要问题。我将下一个指针设置为:
orig_cursor = orig_cursor->next;
我的整个方法如下:
struct node* copyList()
{
if(!head)
return NULL;
struct node *head_copy = malloc(sizeof(struct node));
struct node *copy_cursor = head_copy;
struct node *orig_cursor = head;
head_copy->data = head->data;
head_copy->next = NULL;
if(orig_cursor->next)
{
while(orig_cursor)
{
copy_cursor->next = malloc(sizeof(struct node));
copy_cursor = copy_cursor->next;
printf("Original cursor pre-traversal = %d\n", orig_cursor->next);
orig_cursor = orig_cursor->next;
printf("Original cursor post-traversal = %d\n", orig_cursor->next);
copy_cursor->data = orig_cursor->data;
if(!orig_cursor->next)
{
copy_cursor->next = NULL;
break;
}
}
}
return head_copy;
}
我还使用以下push()函数将节点推送到列表中:
void push(int data)
{
if(!head)
{
head = malloc(sizeof(struct node));
head->data = data;
head->next = NULL;
return;
}
struct node *new_node = malloc(sizeof(struct node));
new_node->data = data;
new_node->next = head;
head = new_node;
}
答案 0 :(得分:0)
尝试使用
struct node * new_node = malloc(sizeof(struct node));