gpt4 book ai didi

C - 链表插入

转载 作者:行者123 更新时间:2023-11-30 18:51:04 25 4
gpt4 key购买 nike

我想创建 5 个节点并在第三个和第四个节点之间插入一个新节点。这是代码。当我运行它时,我没有收到错误或输出。我做错了什么?提前致谢。

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

typedef struct node{

int data;
struct node *next;

}node;


int main(void) {

struct node *root, *newElement, *temp;

// first node is created.
root = (node*)malloc(sizeof(node));
root->data = 11;

// to create 4 nodes more after the first one is created.
int i;
for (i=0; i <= 3; i++){

root->next = (node*)malloc(sizeof(node));
root = root->next;
root->data = (i * 10);

}

// new node to insert.
newElement = (node*)malloc(sizeof(node));
newElement-> data = 1;



temp = (node*)malloc(sizeof(node));

temp = root->next->next;

root->next -> next = newElement;

newElement->next = temp;


// print the values
int j;
for(j=0; j<=4; j++){
root = root->next;
printf("%d\n", root->data);
}


return 0;

}

最佳答案

root = temp = (node*)malloc(sizeof(node));//no need cast from void*
temp->data = 11;

int i;
for (i=0; i <= 3; i++){
//don't change root
temp->next = (node*)malloc(sizeof(node));
temp = temp->next;
temp->data = (i * 10);
}
temp->next = NULL;//next of last node need set to NULL

newElement = (node*)malloc(sizeof(node));
newElement-> data = 1;

//temp = (node*)malloc(sizeof(node));//no need (this make memory leak)
temp = root->next->next;
root->next->next = newElement;
newElement->next = temp;


for(temp = root; temp; temp = temp->next){
printf("%d\n", temp->data);
}

关于C - 链表插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277512/

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