#include <stdio.h>
#include<stdlib.h>
typedef struct twoNode {
int data;
twoNode* prior;
twoNode* next;
}DNode;
DNode* CreateNode(int i) {
DNode* node = (DNode*)malloc(sizeof(DNode));
node->prior = NULL;
node->next = NULL;
node->data = i;
return node;
}
void InsertFive(DNode* h){
for (int i = 1; i <= 5; i++) {
DNode* NewNode = CreateNode(i);
h->next = NewNode;
h = h->next;
}
}
void OutPut(DNode* h) {
h = h->next;
while (h)
{
if (h == NULL)
break;
printf("%d", h->data);
printf("\n");
h = h->next;
}
}
int main() {
DNode* head = (DNode*)malloc(sizeof(DNode));
DNode* h = head;
InsertFive(h);
InsertFive(h);
InsertFive(h);
OutPut(head);
}
运行结果
肯定不对啊,h指针并没有改变位置,你应该插入5个元素前,将h移动到链表尾部节点才是正确的。不然每次h都是头节点,你插入的是头节点之后,但原先的链表就断掉了。
修改如下:(修改处已增加注释)
#include <stdio.h>
#include<stdlib.h>
typedef struct twoNode {
int data;
twoNode* prior;
twoNode* next;
}DNode;
DNode* CreateNode(int i) {
DNode* node = (DNode*)malloc(sizeof(DNode));
node->prior = NULL;
node->next = NULL;
node->data = i;
return node;
}
void InsertFive(DNode* h){
while(h->next != NULL) //每次插入节点时,先将h指向最后一个节点
h = h->next;
for (int i = 1; i <= 5; i++) {
DNode* NewNode = CreateNode(i);
h->next = NewNode;
h = h->next;
}
}
void OutPut(DNode* h) {
h = h->next;
while (h)
{
if (h == NULL)
break;
printf("%d", h->data);
printf("\n");
h = h->next;
}
}
int main() {
DNode* head = (DNode*)malloc(sizeof(DNode));
DNode* h = head;
h->next = NULL; //要初始化头节点的next和prior为空
h->prior = NULL;
InsertFive(h);
InsertFive(h);
InsertFive(h);
OutPut(head);
return 0;
}
void InsertFive(DNode*& h)
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!