【问题标题】:basic questions about Linkedlist and Node Insertion关于链表和节点插入的基本问题
【发布时间】:2020-03-07 18:58:30
【问题描述】:

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

首先,抱歉英语不好。

不管怎样,教授告诉我解题太难了,换几行就行了。

但我无法按时完成此代码。

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

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

}

【问题讨论】:

  • 您的插入节点功能错误。您需要注意列表为空的情况。在这种情况下,需要更新列表的头部。
  • @RishikeshRaje 你能为我解释更多细节吗?如何更新头部?你的意思是“linkedList_h”需要更多代码或修复它?

标签: c data-structures linked-list malloc nodes


【解决方案1】:

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

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

}

【讨论】:

  • 谢谢。现在可以了。我将尝试更多有关此代码的信息。欣赏
猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 2020-09-10
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 2013-02-06
相关资源
最近更新 更多