链表插入失败

来源:百度知道 编辑:UC知道 时间:2024/09/25 05:52:46
我自己定义了一个链表,代码如下:
#include "Stdio.h"
#include "Conio.h"
#include <malloc.h>

#define NULL 0
#define LEN sizeof(struct LNode)

struct LNode
{
int data;
struct LNode * next;
};

int n;/* 全局变量n,各函数都能使用*/

struct LNode * createLinkList()
{
struct LNode * head, *p1, *p2;
n = 0;/*链表中元素的个数*/
p1 = p2 = (struct LNode *)malloc(LEN);/*开辟一个新单元*/
scanf("%d",&p1->data);
head = NULL;
while (p1->data != 0)
{
n = n+1;
if (n == 1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (struct LNode *) malloc(LEN);
scanf("%d",&p1->data);
}
p2->next = NULL;/*表尾*/
return head;
}

void print(struct LNode * head)
{
struct LNode * p;
printf("%s","输出链表:\n");
p = h

只改两个地方就可以了:
struct LNode * insert(struct LNode * head,struct LNode * iList)
{
struct LNode * p1;
p1 = head;
while(p1->next != NULL) //改这里
{
p1 = p1->next;
}
p1->next = iList; //还有这里
iList->next = NULL;

return head;
}

插入函数有错,根本没有完成插入,该函数修改如下:

struct LNode * insert(struct LNode * head,struct LNode * iList)
{
struct LNode * p1;
if (head==NUL) return iList; //空链直接返回插入节点
p1 = head;
while(p1->next != NULL) p1 = p1->next;
p1->next = iList; //插入到最后
return head;
}

你的insert函数里面,while(p1 != NULL)
{
p1 = p1->next;
}
这个循环完了之后p1=NULL的,当然接不上了,改改