童鞋坐等链表插入问题(非常感谢)
// 0910.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdio.h"
#include <iostream>
using namespace std;
#define MAXSIZE 50
typedef struct Node{
int data;
struct Node *next;
}LNode;
void Output(Node *p);
void TailOutput(LNode *p);
// 头插入法建链表
LNode* HeadList(LNode *head)
{
int i;
LNode *p,*h;
h = head;
for(i=0;i<5;i++)
{
p = (struct Node*)malloc(sizeof(struct Node));
p->data = i;
p->next = h->next;
h->next = p;//新创建的节点,总是作为第一个节点
}
return head;
}
/*
为了操作方便,总是在链表的第一个结点之前附设一个头结点(头指针)
head指向第一个结点。头结点的数据域可以不存储任何信息(或链表长度等信息)
*/
//尾插入法建链表
LNode* TailList(LNode *Tail)
{
LNode *p,*t;
t = Tail;
int i;
for (i=0;i<3;i++)
{
p = (struct Node*)malloc(sizeof(struct Node));
p->data = i;
t->next = p;
t = t->next;
}
t->next = NULL;
//free(p);
return Tail;
}
/*
向链表中插入一个节点(插入在末尾)
*/
LNode* insertNode(LNode *l,int value)
{
LNode *p,*t;
t=l->next;
while(t!=NULL)
{
t=t->next;
}
p=(struct Node*)malloc(sizeof(struct Node));
p->data=value;
t->next=p->next;//为什么执行到这里就报错了?
p->next=t;
return l;
}
/*
删除某个节点的值
*/
LNode* DeleteNode(LNode *l,int value)
{
LNode *p,*r;
p=l;
while(p!=NULL)
{
r=p->next;//p指向头节点,而头节点在定义时仅仅是一个节点,因此把头节点的下一个节点(第一个节点)
if (r->data==value)
{
p->next=r->next;
return l;
}
p=p->next;
}
return l;
}
void Output(Node *p)
{
Node *l;
l = p->next;
while(l!=NULL)
{
printf("%d\n",l->data);
l = l->next;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
LNode *tmp;
Node *head,*p,*l;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = NULL;
// tmp = HeadList(head);
//Output(tmp);
tmp = TailList(head);
tmp = insertNode(tmp,5);
//tmp = DeleteNode(tmp,1);
Output(tmp);
getchar();
return 0;
}
问题:
我的目的是在链表末尾插入数据,看了两天了没有找到问题所在,求高手帮忙
-------------------------
LNode* insertNode(LNode *l,int value)
{
LNode *p,*t;
t=l->next;
while(t!=NULL)
{
t=t->next;
}
p=(struct Node*)malloc(sizeof(struct Node));
p->data=value;
t->next=p->next;//为什么执行到这里就报错了?
p->next=t;
return l;
}
这个插入操作那里有错了呢。
[解决办法]
while循环结束的时候 t=NULL
NULL是没有next的。。。所以给t->next赋值的时候出错了
应该是
。。。
t=l;
while(t->next!=NULL)
{
t=t->next;
}
。。。
t->next=p;
p->next=NULL;
。。。
[解决办法]