c-链表填充空列表


struct Node
{
int val;
struct Node *next;
};
struct List
{
struct Node *head;
struct Node *tail;
int size;
};
typedef struct List *List;

这是我的节点和列表,我想通过在每次迭代中创建一个新节点,将每个I值逐一添加到节点中,但我的程序崩溃了,我不知道的原因是什么

int i;
List origin;
List myList = (struct List*)malloc(sizeof(struct List));
myList->head = (struct Node*)malloc(sizeof(struct Node));
myList->head->next = NULL;
myList->tail = myList->head;
origin=myList;

for(i=0;i<5;i++)
{
myList->head->next = (struct Node*)malloc(sizeof(struct Node));
myList->head->next->val = i;
myList->head->next = myList->head->next->next;
myList->head->next->next = NULL;           
}

少数问题:

  • 您根本没有遍历列表
  • 您正在破坏列表head指针,而没有更新tail指针
  • 您正在使用head作为虚拟节点。将它的值设置为一些特殊的标记是一种很好的做法,比如-1
  • 最好使用临时temp节点进行遍历,使用newnode插入新节点,以避免未初始化的指针访问和分配

修改的main()函数:

int main()
{
int i;
// List origin;
List myList = (struct List*)malloc(sizeof(struct List));
myList->head = (struct Node*)malloc(sizeof(struct Node));
myList->head->val = -1; /* Set a value to the dummy first node */
myList->head->next = NULL;
myList->tail = myList->head;
// origin = myList;

struct Node* temp = myList->head; /* Use a temporary pointer to traverse */
for(i=0;i<5;i++)
{
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->val = i;
newnode->next = NULL;

temp->next = newnode;
temp = newnode;         /* Update temporary head to the new node */
myList->tail = newnode; /* Update the tail to last node */
}
temp = myList->head;
while(temp != NULL)
{
printf("%d", temp->val);
if(temp != myList->tail)
printf("->");
temp = temp->next;
}
return 0;
}

结果:

-1->0->1->2->3->4

在处理完列表后,还要小心使用free()释放malloced内存。我也不明白List origin的目的,所以我把那部分评论掉了。

要找到问题,我们可以添加一些调试输出:

for(i=0;i<5;i++)
{
myList->head->next = (struct Node*)malloc(sizeof(struct Node));
printf("myList->head->next = %pn", myList->head->next);
myList->head->next->val = i;
printf("myList->head->next->next = %pn", myList->head->next->next);
myList->head->next = myList->head->next->next;
printf("myList->head->next = %pn", myList->head->next);
if (NULL == myList->head->next) {
printf("We just set our next pointer to NULL, so we should stop now.n");
exit(1);
}
myList->head->next->next = NULL;
}

我们得到这个输出:

myList->head->next = 0x7f8062c05800
myList->head->next->next = 0x0
myList->head->next = 0x0
We just set our next pointer to NULL, so we should stop now.

我对初始化循环做了以下更改:

struct Node *current = myList->head;
for(i=0;i<5;i++)
{
current->next = (struct Node*)malloc(sizeof(struct Node));
current->next->val = i;
current->next->next = NULL;
current = current->next;
}

我还添加了一个输出循环来验证初始化是否有效:

current = myList->head->next;
while (current) {
printf("%p = %dn", current, current->val);
current = current->next;
}

输出

0x7fced6405800 = 0
0x7fced6405810 = 1
0x7fced6405820 = 2
0x7fced6405830 = 3
0x7fced6405840 = 4

注意

你没有用尾标做任何事情,所以我会让你想办法处理它。

相关内容

  • 没有找到相关文章