[英]C++ Linked Lists and Pointers to Pointers
第一篇文章,但我已经潜伏了一段时间:)
首先,我正在尝试在Visual Studio 2015中执行此框架代码,根据我的老师的说法,它应该可以正常工作,因此我不确定还有哪些其他错误的客户端可能会导致这种情况。
最后,这里的总体问题是我不确定如何完成剩余命令。 我了解指针的工作原理以及链接列表的基本概念,但并不完全。 我的第一个问题也没有帮助。
任何帮助将不胜感激。
谢谢,
一些
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int value;
struct _node *next;
} node;
void append(node**, int);
void prepend(node**, int);
void lprint(node*);
void destroy(node*);
int main(int argc, char **argv)
{
node *head = NULL;
append(&head, 1);
append(&head, 2);
append(&head, 3);
prepend(&head, 0);
prepend(&head, -1);
prepend(&head, -2);
lprint(head);
destroy(head);
return 0;
}
void append(node **head, int value)
{
if (*head == NULL)
{
*head = (node*)calloc(0, sizeof(node));
(**head).value = value;
}
else
{
node *temp;
for (temp = *head; (*temp).next != NULL; temp = temp->next);
(*temp).next = (node*)calloc(0, sizeof(node));
(*temp).(*next).value = value;
}
}
void prepend(node **head, int value)
{
}
void lprint(node *head)
{
node *temp;
for (temp = head; temp != NULL; temp = temp->next)
{
printf("%d ", temp->value);
}
printf("\n");
}
void destroy(node *head)
{
}
更改此行后,我能够编译并运行您的代码:
(*temp).(*next).value = value;
对此:
(*temp).next->value = value;
当我运行它时,它打印出来:
1 2 3
鉴于未实现prepend(),这是我期望的。
我可以编写prepend()
的实现并将其发布到此处,但是我不想冒着为您做功课的风险; 相反,我只会描述prepend()
应该如何工作。
对于head
为NULL的情况, prepend()
可以做与append()
完全相同的事情:分配一个节点并将head
设置为指向该节点。
在另一种情况下, head
为非NULL(因为列表为非空),也很容易-甚至比append()
实现容易。 您需要做的就是分配新节点,将新节点的next
指针设置为指向现有的head
节点(* head),然后将head
指针(* head)设置为指向新节点。
该destroy()
函数可以用非常类似于一个在你的循环工作lprint()
你必须抓住-功能,有一点需要注意next
你之前指针出给定节点的(并存储到一个局部变量) free()节点,因为如果先释放该节点,然后尝试从已释放的节点读取下一个指针,则您正在读取已释放的内存,这是一个no-no(未定义的行为),并且会导致错误事情(tm)发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.