#includestdioh#includestddefh#includeiostreamusing namespace std; typedef int ElemType;typedef struct LNode ElemType data; struct LNode next;LNodeLinkList;int InitListLinkList &L L=new LNode; L-next=N
在代码中有以下几处错误:
-
在ListInsert函数中,没有正确实现插入节点的功能。应该先找到要插入位置的前一个节点,然后新建一个节点并赋值,最后将新节点插入到链表中。
-
在CreatList函数中,没有定义指针p。应该先定义p,然后根据输入的数据新建节点并插入到链表中。
-
在print函数中,应该使用cout来输出数据,而不是使用printf。
以下是修改后的代码:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
int InitList(LinkList &L)
{
L = new LNode;
L->next = NULL;
return 1;
}
int ListInsert(LinkList &L, int i, ElemType e)
{
LNode *p = L;
int j = 0;
while (p && j < i - 1) {
p = p->next;
j++;
}
if (!p || j > i - 1) {
return 0;
}
LNode *newNode = new LNode;
newNode->data = e;
newNode->next = p->next;
p->next = newNode;
return 1;
}
void CreatList(LinkList &L, int n)
{
L = new LNode;
L->next = NULL;
LNode *p = L;
for (int j = 0; j < n; j++)
{
LNode *newNode = new LNode;
cin >> newNode->data;
newNode->next = p->next;
p->next = newNode;
p = p->next;
}
}
void print(LinkList L)
{
LNode *p = L->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
}
int main()
{
LinkList L = NULL;
InitList(L);
CreatList(L, 5);
print(L);
return 0;
}
修改后的代码将能够正确初始化链表、插入节点、创建链表并输出链表的节点数据。
原文地址: https://www.cveoy.top/t/topic/jaqN 著作权归作者所有。请勿转载和采集!