有关链表和节点插入的基本问题

我的次要专业讲座有些问题。

首先,对不起,英语不好。

无论如何,教授告诉我,解决问题是东方的,只需更改一些行就可以了。

但是我不能准时完成这段代码。

我玩什么时候?调试?我的代码无法打印“列表”。

如何正确打印我的LinkedList代码? +我必须修正几行。不是完整的代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>  


typedef struct ListNode {
    int data;
    struct ListNode* link;
}listNode;


void insertFirstListNode(listNode* num,int data) {
    listNode* newNode = malloc(sizeof(listNode));
    newNode->link = num->link;
    newNode->data = data;
    num->link = newNode;
}

typedef struct {
    listNode* head;
} linkedList_h;


linkedList_h* createLinkedList_h() {
    linkedList_h* Newlist = (linkedList_h*)malloc(sizeof(linkedList_h));
    Newlist->head = NULL;       
    return Newlist;
}



void printList(linkedList_h* L) {
    listNode* p;
    printf("L = (");
    p = L->head;
    while (p != NULL) {
        printf("%d",p->data);
        p = p->link;
        if (p != NULL) printf(",");
    }
    printf(") \n");
}



void main() {
    linkedList_h* m;
    m = createLinkedList_h();
    insertFirstListNode(m,10);
    printList(m);

}
huang118118bing 回答:有关链表和节点插入的基本问题

根据我的理解,您正在尝试将节点添加到链接列表的开头。在这种情况下,以下修复程序应该可以正常工作。

请在所有功能(例如NULL输入,Malloc失败等)中进行错误处理...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>  


typedef struct ListNode {
    int data;
    struct ListNode* link;
}listNode;

typedef struct {
    listNode* head;
} linkedList_h;



void insertFirstListNode(linkedList_h* num,int data) {
    listNode* newNode = (listNode *)malloc(sizeof(listNode));
    newNode->link = num->head;
    newNode->data = data;
    num->head = newNode;
}


linkedList_h* createLinkedList_h() {
    linkedList_h* Newlist = (linkedList_h*)malloc(sizeof(linkedList_h));
    Newlist->head = NULL;       
    return Newlist;
}



void printList(linkedList_h* L) {
    listNode* p;
    printf("L = (");
    p = L->head;
    while (p != NULL) {
        printf("%d",p->data);
        p = p->link;
        if (p != NULL) printf(",");
    }
    printf(") \n");
}



int main() {
    linkedList_h* m;
    m = createLinkedList_h();
    insertFirstListNode(m,10);
    printList(m);
    return 0;

}
本文链接:https://www.f2er.com/3119832.html

大家都在问