我已经在C中编写了此代码以实现链接列表。虽然语义和语法很好,但它无法正常工作。例如,当我将1插入列表然后打印链接列表时,它显示列表为空。
#include<stdio.h>
#include<stdlib.h>
struct node {
int info;
struct node *next;
}; typedef struct node Node;
void addNode(Node *head, int x)
{
Node *temp;
temp=malloc(sizeof(temp));
temp->info=x;
if (head==NULL)//if this is the first node in the list
{
head=temp;
temp->next=NULL;
}
else //if not, add it as the head
{
temp->next=head;
head=temp;
}
}
void appendNode(Node *head, int x)
{
Node *rear =head;
Node *temp= malloc(sizeof(temp));
temp->info=x;
temp->next=NULL;
while (rear->next!=NULL)
rear=rear->next;
rear->next=temp;
rear=temp;
}
void insertNodeafter(Node *head, int location, int x)
{
int i;
Node *before, *after = head;
Node *temp= malloc(sizeof(temp));
temp->info=x;
for (i=0;i<location;i++)
before=before->next;
after=before->next;
temp->next=after;
before->next=temp;
}
void insert(Node *head, int x)
{
int c=0;
Node *temp;
temp=head;
if(temp==NULL)
{
addNode(temp,x);
}
else
{
while(temp!=NULL)
{
if(temp->info<x)
c++;
temp=temp->next;
}
if(c==0)
addNode(temp,x);
else if(c<listSize())
insertNodeafter(temp,x,++c);
else
appendNode(temp,x);
}
}
int listSize()
{
Node *head, *n;
int c=0;
n=head;
while(n!=NULL)
{
n=n->next;
c++;
}
return c;
}
void DisplayLinkedList(Node* head)
{
Node *rear=NULL;
if (head==NULL)
printf("list is empty!n");
else
{
rear=head;
while (rear!=NULL)
printf("%d |---> ", rear->info);
rear=rear->next;
}
}
int getNextNode(Node *head)
{
if (head == NULL)
return -1;
else
return head->next->info;
}
Node* deleteNode(Node *head, int x)
{
Node *temp;
if (head == NULL)
return NULL;
else
{
if (head->info==x)
{
temp = head->next;
free(head);
head=temp;
return head;
}
else
{
deleteNode(head->next,x);
return head;
}
}
}
void main()
{
int i=0;
Node *myNode;
insert(myNode,1);
DisplayLinkedList(myNode);
}
,因为您使用的是Node*
变量,而不是在函数参数中使用Node**
变量。由于您使用的是Node*
,因此在变量head
中完成的更改是该功能的本地化。如果您想在函数调用后反映这些更改(显然您想(,请使用Node**
并在代码中相应地使用。
正如上一个海报所述,最好使用node **变量来反映函数调用后的更改。如果您想使用节点*,则必须返回节点*返回主。
我使用addNode,Insert和displayLinkedList删除您的代码,以添加1,现在它与下面的代码正确显示。
您还应该将节点*设置为NULL,以初始化空链接列表。检查您的displayLinkedList函数 - 您在循环中缺少卷曲括号。它只是读取printf线而不读取列表,导致无限循环。
最佳实践是在创建此程序时进行调试和测试。
#include<stdio.h>
#include<stdlib.h>
#include "stack.h"
void main()
{
int i=0;
Node *myNode;
myNode = NULL;
insert(&myNode,1);
DisplayLinkedList(myNode);
}
void addNode(Node **head, int x)
{
Node *temp;
temp=malloc(sizeof(temp));
temp->info=x;
if (*head==NULL)//if this is the first node in the list
{
*head=temp;
temp->next = NULL;
}
else //if not, add it as the head
{
temp->next=*head;
*head=temp;
}
}
void insert(Node **head, int x)
{
int c=0;
Node *temp;
temp=*head;
if(temp==NULL)
{
addNode(head ,x);
}
}
void DisplayLinkedList(Node* head)
{
Node *rear=NULL;
if (head==NULL)
printf("list is empty!n");
else
{
rear=head;
while (rear!=NULL)
{
printf("%d |---> ", rear->info);
rear=rear->next;
}
}
}