InsetNodeError函数内直接定义一个LNode结构体,而InsetNode使用的是结构体指针
最终在vs2017上第一种在打印输出时失败,第二种正常。
int InsetNodeError(LinkList &L, int i, ElemType e)
{
LNode* p = L;
int j = 0;
LNode s;
s.data = e;
while (p && (j < i - 1))//找到第i-1个节点,p指向它,当i=1;p为头节点
{
p = p->next;
j++;
}
s.next = p->next;
p->next = &s;
return OK;
}
int InsetNode(LinkList &L, int i, ElemType e)
{
LNode* p = L;
int j = 0;
LNode* s;
s = new LNode;
s->data = e;
while (p && (j < i - 1))//找到第i-1个节点,p指向它,当i=1;p为头节点
{
p = p->next;
j++;
}
s->next = p->next;
p->next = s;
return OK;
}
附上全部程序
#include
#include
#define ERR -1
#define OK 1
#define ElemType int
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,* LinkList;
int InitList(LinkList &L)
{
L = new LNode;
L->next = NULL;
return OK;
}
//获取第i为元素,并返回到e
int GetElem(LinkList L, int i, ElemType &e)
{
LNode *p=L;
while (i)
{
p = p->next;
i--;
}
e = p->data;
return OK;
}
//查找节点返回节点的地址
LNode* LocateElem(LinkList &L, ElemType e)
{
LNode* p = L->next;
while ( p && p->data != e )
{
p = p->next;
}
if (p == NULL)
printf("查找失败!!!\n");
return p;
}
//在第i个位置插入元素s
int InsetNodeError(LinkList &L, int i, ElemType e)
{
LNode* p = L;
int j = 0;
LNode s;
s.data = e;
while (p && (j < i - 1))//找到第i-1个节点,p指向它,当i=1;p为头节点
{
p = p->next;
j++;
}
s.next = p->next;
p->next = &s;
return OK;
}
int InsetNode(LinkList &L, int i, ElemType e)
{
LNode* p = L;
int j = 0;
LNode* s;
s = new LNode;
s->data = e;
while (p && (j < i - 1))//找到第i-1个节点,p指向它,当i=1;p为头节点
{
p = p->next;
j++;
}
s->next = p->next;
p->next = s;
return OK;
}
int ListDel(LinkList &L, int i)
{
LNode* p = L; int j = 0;
while (p->next && (j < i - 1))
{
p = p->next;
j++;
}
LNode* q = p->next;
p->next = q->next;
delete q;
return OK;
}
int CreatListHead(LinkList &L, int n)
{
LNode* p;
L = new LNode;
L->next = NULL;
for (int i = 0; i < n; i++)
{
p = new LNode;
printf("输入第%d位元素的值\n ",i);
scanf_s("%d", &(p->data));
p->next = L->next;
L->next = p;
}
return OK;
}
int CreatListTail(LinkList &L, int n)
{
LNode* p;
LNode* r;//尾指针
L = new LNode;
L->next = NULL;
r = L;
for (int i = 0; i < n; i++)
{
p = new LNode;
printf("输入第%d位元素的值\n ",i+1);
scanf_s("%d", &(p->data));
p->next = NULL;
r->next = p;
r = p;
}
return OK;
}
void PrintLinkList(LinkList &L)
{
LNode* p = L->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
LinkList M=NULL;
CreatListTail(M, 4);
InsetNode(M, 5, 5);
PrintLinkList(M);
system("pause");
return 0;
}