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

kmbjn2e3  于 2022-12-03  发布在  其他
关注(0)|答案(1)|浏览(174)

我无法得到在给定节点的开头、结尾和后面插入节点的输出。我不确定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
但我没有得到输出,也没有错误

oewdyzsn

oewdyzsn1#

在函数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;
}

相关问题