#include "List.h"
typedef int element;
typedef struct _ListNode //form of node
{
element data;
struct ListNode *link;
} ListNode;
ListNode *header = NULL; //make header in global variable
int num_node = 0; //counting number of nodes
int AppendNode(const ListNode item);
void DisplayItem(void);
int InsertNode(const int pos, const ListNode item);
int AppendNode(const ListNode item)
{
ListNode *current, *new_item = NULL;
new_item = (ListNode *)malloc(sizeof(ListNode));
if (new_item == NULL) return 0;
new_item->data = item.data;
new_item->link = NULL;
if (header == NULL)
header = new_item;
else{
current = header;
while (current->link != NULL)
{
current = current->link;
current->link = new_item;
}
}
num_node++;
return 1;
}
void DisplayItem(void) //print all the nodes
{
ListNode *current = NULL;
current = header;
while (current != NULL)
{
printf("%d\n", current->data); //MEMORY ACCESS PROBLEM
current = current->link;
}
}
int InsertNode(const int position, const ListNode item)
{
ListNode *current = NULL;
ListNode *new_item = NULL;
new_item = (ListNode *)malloc(sizeof(ListNode));
if (new_item == NULL) return 0;
if (position == 1)
{
new_item->link = header;
header = new_item;
num_node++;
}
else if((1 < position) && (position < num_node))
{
int current_position = 0;
current = header;
while (current_position != (position - 1))
{
current = current->link;
current_position++;
}
new_item->link = current->link;
current->link = new_item;
num_node++;
}
else return 0;
}
int main(void)
{
ListNode node1; node1.data = 10;
DisplayItem();
getchar();
return 0;
}
我想制作简单的链表程序。但由于内存访问问题,它无法正常工作。 此外,我再创建两个节点,但除了节点1之外,它不会被追加。 我想使用Call-by-Reference。并且所有函数都应该是结果0,1。
0 - fail.
1 - success.
看起来不舒服,但......我怎么能让这个工作?
答案 0 :(得分:0)
请在下面的评论中查看您的简单错误,并尝试下面的更正: -
typedef struct _ListNode //form of node
{
element data;
struct ListNode *link;/* here it should be _ListNode */
} ListNode;
现在请看下面的方法你犯了错误
int AppendNode(const ListNode item)
{
ListNode *current, *new_item = NULL;
new_item = (ListNode *)malloc(sizeof(ListNode));
if (new_item == NULL) return 0;
new_item->data = item.data;
new_item->link = NULL;
if (header == NULL)
header = new_item;
else{
current = header;
while (current->link != NULL)
/* here in the above while statement current->link always NULL because it is pointing to the first node and first->next == NULL. Hence this while loop will never execute and link list will not be created because you have assign the new node inside this while loop. Move the code out side of this loop */
{
current = current->link;
current->link = new_item;
}
}
正确的循环应该是
while (current->link != NULL)
{
current = current->link;
}
current->link = new_item; /* this line of code should be out side of while loop */
num_node++;
return 1;
}
Just correct the while loop like above in function AppendNode as well.
Now it will work fine