C语言 我试图在链表中插入节点的逻辑错误是什么?



我无法获得在给定节点的开始、结束和之后插入节点的输出。我不太确定在main()中是否遗漏了什么。我无法指出程序中的逻辑错误'

#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
//Inserts at the begining
void push(struct node **head, int x){
struct node *newnode = (struct node *)malloc(sizeof(struct node));
newnode->data = x; 
*head = newnode;
newnode->next = (*head);
*head = newnode;
}
//Insert at the last 
void append(struct node **head, int x){
struct node *temp;
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = x;
newnode->next = 0;
if(*head == 0){
*head = newnode;
}
temp = *head;
while(temp->next != 0){
temp = temp->next;
}
temp->next = newnode;
}
//inserting at a given node 
void insertAfter(struct node* temp, int x){
if(temp == NULL){
printf("previous node cannot be NULL");
}
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = x;
newnode->next = temp->next;
temp->next = newnode;   
}
void printList(struct node *temp){
while(temp->next != NULL){
printf("%d",temp->data);
}
temp = temp->next;
}
int main(){
struct node *head = NULL;
append(&head,6);
push(&head, 7);
push(&head, 1);
append(&head, 4);
insertAfter(head->next, 8);
printf("Created linked list is:n"); 
printList(head);
return 0;
}

输出为1 7 8 6 4

但是我没有输出,也没有错误

在函数print_list中可以有一个无限循环,因为下面的语句

temp = temp->next;

放在while循环

之后
void printList(struct node *temp){
while(temp->next != NULL){
printf("%d",temp->data);
}
temp = temp->next;
}

函数可以如下方式查找示例

void printList( const struct node *head )
{
for ( ; head != NULL; head = head->next )
printf( "%d -> ", head->data );
}
puts( "null" );
}

注意在函数push中这个语句

*head = newnode;

出现两次。

而且函数是不安全的,因为没有检查是否在函数内成功分配了内存。

例如,append函数可以如下方式声明和定义

//Insert at the last 
int append( struct node **head, int x )
{
struct node *newnode = malloc( sizeof( *newnode ) );
int success = newnode != NULL;
if ( success )
{
newnode->data = x;
newnode->next = NULL;
while ( *head != NULL ) head = &( *head )->next;
*head = newnode;
}
return success;
}

相关内容

  • 没有找到相关文章

最新更新