这是一个关于链表的取值问题


#include<iostream>
#include<conio.h>
#include<string>
#include<iostream>
#include<conio.h>
using namespace std;
#define OK 1;
#define ERROR -1;
typedef int Status;
typedef struct 
{
string name;
float price;
}Book;
typedef  Book ElemType;
typedef struct  LNode 
{
ElemType     Elem;
LNode *Next;
}LNode,*List;
Status InitList( List &L)
{

    L=new LNode();
    L->Next=NULL;
    return OK;
}

Status Q(List &tou,int n)
{
tou=new LNode();
while(n>=0)
{

List P=new LNode();
P->Next=tou->Next;
tou->Next=P;
n--;
return 0;
}
}
Status GetValue(List L,int n,ElemType Elem)
{
List P=L->Next; int j=1;
while(P&&j<n)
{
P=P->Next;
++j;

}
if(!P||j<n)
return ERROR;
Elem=P->Elem;
return OK;
}

int main()
{

    int a=1;
    List L;
    InitList(L);
    Q(L,4);
    ElemType en;
    GetValue(L,2,en);

getch();


return 0;
}



这是我写的链表代码,做了前插法生成链表(Q函数),还有头结点初始化函数(InitList)。最后想搞个链表取值函数getvalue()。写完后,编译没有问题。但是运行的话,会溢出,求解。

#include<iostream>
#include<conio.h>
#include<string>
#include<iostream>
#include<conio.h>
using namespace std;
#define OK 1;
#define ERROR -1;
typedef int Status;
typedef struct 
{
    string name;
    float price;
}Book;
typedef  Book ElemType;
typedef struct  LNode 
{
    ElemType     Elem;
    LNode *Next;
}LNode,*List;
Status InitList( List &L)
{

    L=new LNode();
    L->Next=NULL;
    return OK;
}

Status Q(List &tou,int n)
{
    tou=new LNode();
    tou->Next = NULL; //加上
    while(n>=0)
    {
        List P=new LNode();
        cout << "n=" << n << "\tname:";
        cin >> P->Elem.name;
        cout << "\tprice:";
        cin >> P->Elem.price;
        P->Next=tou->Next;
        tou->Next=P;
        n--;
    }
    return 0;
}
Status GetValue(List L,int n,ElemType * Elem) //这里用指针,才能传回来
{
    List P=L->Next; int j=1;
    while(P&&j<n)
    {
        P=P->Next;
        ++j;

    }
    if(!P||j<n)
        return ERROR;
    *Elem=P->Elem;
    return OK;
}

int main()
{

    int a=1;
    List L;
    InitList(L);
    Q(L,4);
    ElemType en;
    GetValue(L,2,&en);
    cout << "get 2: ";
    cout << en.name << " " << en.price;
    getch();
    return 0;
}

Q函数里面,你在while 循环里面就return出去了

这个是你溢出异常的主要原因

但你这个程序好多错误

内存泄漏,还有很多地方都不是很符合规范