我正在编写一个程序,它可以将元素插入到列表的末尾,然后显示其中一个。它插入正确,但我可以显示指定的。
typedef struct Node
{
int data;
struct Node *next;
struct Node *prev;
} node;
void insert(node *head, int data)
{
node *newNode = (node*) malloc(sizeof(node));
newNode->data = data;
newNode->next = NULL;
if(head == NULL)
{
head = newNode;
}
else
{
while(head != NULL)
head = head->next;
head->next = newNode;
(head->next)->prev = head;
}
}
void print(node *head, int element)
{
node *temp = head;
int count = 0, i = 1;
while(i < element)
{
temp = temp->next;
i++;
}
printf("%d", temp->data);
}
int main()
{
node *start = (node*) malloc(sizeof(node));
start = NULL;
int data1 = 4, data2 = 5;
insert(start,data1);
insert(start,data2);
print(start, 1);
}
为什么它不起作用?另外,你能告诉我我这样做是否正确吗?