gpt4 book ai didi

c - 关于链表和节点插入的基本问题

转载 作者:行者123 更新时间:2023-11-30 16:10:43 25 4
gpt4 key购买 nike

我对我的副专业讲座有一些问题。

首先,抱歉英语不好。

无论如何,教授告诉我,解决起来很简单,只需更改一些行即可。

但我无法按时完成这段代码。

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

如何正确打印我的 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);

}

最佳答案

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

请在所有函数中进行错误处理,例如 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;

}

关于c - 关于链表和节点插入的基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58812373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com