65,187
社区成员




LinkList.h
typedef struct LNode
{
int nData;
LNode *pNext;
}LinkList;
bool InitLinkList(LinkList *L, const int arrData[], const int nLength);
bool DisplayLinkList(const LinkList *L);
LinkList.cpp
#include <iostream>
#include "LinkList.h"
using namespace std;
bool InitLinkList(LinkList *L, const int arrData[], const int nLength)
{
L = (LinkList *)malloc(sizeof(LinkList));
L->pNext = NULL;
LNode *pNode = NULL;
for (int i = 0; i < nLength; i++)
{
pNode = (LNode *)malloc(sizeof(LNode));
if (NULL == pNode)
{
printf("InitList Failed!");
return false;
}
pNode->nData = arrData[i];
pNode->pNext = L->pNext;
L->pNext = pNode;
}
return true;
}
bool DisplayLinkList(const LinkList *L)
{
if (NULL == L->pNext)
{
return false;
}
LNode *pNode = L->pNext;
while (NULL != pNode->pNext) //就到这里就过不去了
{
cout << 1 << endl;
cout << pNode->nData << ",";
pNode = pNode->pNext;
}
cout << pNode->nData << endl;
return true;
}
main.cpp
#include "LinkList.h"
int main(int argc, char* argv[])
{
LinkList List;
int Array[10] = {2, 3, 5, 8, 9, 11, 34, 101, 66, 90};
if( !InitLinkList(&List, Array, sizeof(Array)/sizeof(int)) )
{
return -1;
}
if (!DisplayLinkList(&List))
{
return -1;
}
return 0;
}
bool InitLinkList(LinkList *L, const int arrData[], const int nLength);
bool InitLinkList(LinkList *&L, const int arrData[], const int nLength);
//LinkList.cpp
#include <iostream>
#include "LinkList.h"
using namespace std;
bool InitLinkList(LinkList *L, const int arrData[], const int nLength)
{
L->pNext = NULL;
LNode *pNode = NULL;
for (int i = 0; i < nLength; i++)
{
pNode = (LNode *)malloc(sizeof(LNode));
if (NULL == pNode)
{
printf("InitList Failed!");
return false;
}
pNode->nData = arrData[i];
pNode->pNext = L->pNext;
L->pNext = pNode;
}
return true;
}
bool DisplayLinkList(const LinkList *L)
{
if (NULL == L->pNext)
{
return false;
}
LNode *pNode = L->pNext;
while (NULL != pNode->pNext) //就到这里就过不去了
{
cout << 1 << endl;
cout << pNode->nData << ",";
pNode = pNode->pNext;
}
cout << pNode->nData << endl;
return true;
}
bool InitLinkList(LinkList *L, const int arrData[], const int nLength)
{
//L = (LinkList *)malloc(sizeof(LinkList)); //已经是对象了,还要分配干嘛?
L->pNext = NULL;
LNode *pNode = NULL;
LNode *pLast = L;
for (int i = 0; i < nLength; i++)
{
pNode = (LNode *)malloc(sizeof(LNode));
if (NULL == pNode)
{
printf("InitList Failed!");
return false;
}
pNode->nData = arrData[i];
pNode->pNext = NULL;
//pNode->pNext = L->pNext;
//L->pNext = pNode; //原地踏步?
pLast->pNext = pNode;
pLast = pNode;
}
return true;
}