1
#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。C:內存中的簡單鏈接列表訪問錯誤
0 - fail.
1 - success.
它看起來很不舒服,但...我怎麼能做這個工作?
我建議你在調試器中逐行執行代碼。有幾段代碼非常錯誤。例如'AppendNode'中的循環。我建議你仔細看看它。 –
在while循環中,你應該只臨時扼殺'current = current-> next',並且一旦你離開while循環,分配'current-> link = new_item'。 'while(current-> link!= NULL){current = current-> link; } current-> link = new_item;'是正確的。這是@Someprogrammerdude提到的一點。 – tilz0R
您尚未創建鏈接列表。你的'*頭部'始終是NULL。 – Gaurav