c - 我无法在链表中使用链表

标签 c function linked-list singly-linked-list definition

当我开始学习链表时,我有了一个想法。我的想法是这样的。我想将 1,2,5 插入到链表中。在链表的另一个字段中,我想添加以 1、2、5 开头的 2 位数字。你可以从图像中看到。 (C 表示组合) https://imgur.com/a/zmEqfPO

int main() {
struct Node* head = NULL;
insertEnd(&head,1);
insertEnd(&head,2);
insertEnd(&head,5);
printLinkedList(head);
insertStartsWith(&head,5,51);
insertStartsWith(&head,5,52);
insertStartsWith(&head,5,53);
insertStartsWith(&head,5,54);
insertStartsWith(&head,1,11);
insertStartsWith(&head,1,12);
insertStartsWith(&head,1,13);
insertStartsWith(&head,1,14);
insertStartsWith(&head,2,21);
insertStartsWith(&head,2,22);
insertStartsWith(&head,2,23);
insertStartsWith(&head,2,24);
printLinkedListWithStartsWith(head);}

我的节点结构:

struct Node {
int data;
struct Node* next;
struct Node* startsWith; };

我插入初始链表 1,2 和 5 的代码:

void insertEnd(struct Node **pNode, int data){
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
struct Node *lastNode=*pNode;
newNode->data=data;
newNode->next=NULL;
if (*pNode==NULL)
{
    *pNode=newNode;
    return;
}
while (lastNode->next!=NULL){
    lastNode=lastNode->next;
}
lastNode->next=newNode;
return; }

这部分是搜索号码,并在它的 startsWith 节点中插入 2 位数字。

void insertStartsWith(struct Node **pNode, int i, int i1) {
struct Node *tempNode=*pNode;
while (tempNode->next!=NULL){
    if (tempNode->data==i){
        struct Node *tempNode1=tempNode->startsWith;
        while (tempNode1->next!=NULL){
            tempNode1=tempNode1->next;
        }
        struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
        newNode->data=i1;
        newNode->next=NULL;
        tempNode1->next=newNode;
        return;
    }
    tempNode=tempNode->next;
} }

我将 1 2 和 5 添加到我的链表中。但是当我尝试添加组合时它失败了。我应该在哪里查找链表中的链表?

编辑 08.18.19

void printLinkedListWithStartsWith(struct Node *pNode) {
printf("Linked list with starts: ");
while (pNode!=NULL) {
    printf("%d \n",pNode->data);
    while(pNode->startsWith!=NULL){
        printf("%d ",pNode->startsWith->data);
        pNode->startsWith=pNode->startsWith->next;
    }
    pNode=pNode->next;
} }

最佳答案

将两个结构相互用于链表的链表可以清楚地表明:

typedef struct List List;
typedef struct Node Node;

struct Node{
    size_t size;
    int value;
    Node* node;
    List *list_value;

};

struct List{
    size_t size;
    Node* node;
};

并且您可以编写函数将数据插入列表:

//Inserts list into listP
void list_set_list_value(List* listP, size_t index, List * list_valueP){
        (*listP).node[index].list_value=list_valueP;
}

//Inserts value into listP
void list_set_int_value(List* listP, size_t index, int valueP){
        (*listP).node[index].value=valueP;
}

关于c - 我无法在链表中使用链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57523154/

相关文章:

c - 如何设置gcc -E深度(预处理级别)?

C 中的自定义函数在 Red Hat Linux 中不起作用,但在 HPUX 中可以

c - 我的函数不记住链表的头

c - C语言中如何对链表进行排序?

输入字符后代码块崩溃,同时还执行其他一些代码

比较C中的两个字符串?

c - 右移 float 的二进制表示 -0.0

clojure - Clojure 使用哪些命名空间进行定义

python - 使用方法自动验证函数参数

c++ - 如何使用递归返回单链表中的倒数第 n 个元素?