C++中链表的一些操作
//C++中链表的一些操作,VS2005下调试通过。
#include <Windows.h>
#include <iostream>
using namespace std;
struct Node
{
int nData;
Node* pNext;
Node(){
nData = 0;
pNext = NULL;
};
};
Node* CreateList(Node* pList, int nCount);
Node* InsertHead(Node* pList, int nData);
Node* InsertTail(Node* pList, int nData);
Node* InsertNode(Node* pList, int nPos, int nData);
Node* ReversalList(Node* pList);
void freeList(Node* pList);
void CoutList(Node* pList);
int GetCount(Node* pList);
int main()
{
cout<<"hello world!"<<endl;
Node* pList = NULL;
pList = CreateList(pList, 10);
CoutList(pList);
cout<<"Begin Insert!"<<endl;
pList = InsertHead(pList,3519);
CoutList(pList);
cout<<endl;
pList = InsertTail(pList,3519);
pList = InsertNode(pList,3,3519);
pList = InsertNode(pList,3,3519);
pList = InsertNode(pList,3,3519);
cout<<"End Insert"<<endl;
CoutList(pList);
cout<<"ReversalList!"<<endl;
CoutList(ReversalList(pList));
cout<<"End ReversalList!"<<endl;
freeList(pList);
cin.get();
return 0;
}
Node* ReversalList(Node* pList)
{
Node* mid = NULL;
Node* last = NULL;
while(pList != NULL){
last = mid;
mid = pList;
pList = pList->pNext;
mid->pNext = last;
}
return mid;
}
void freeList(Node* pList)
{
if(NULL == pList) return;
Node* pfree = NULL;
while(pList != NULL)
{
pfree = pList;
pList = pList->pNext;
delete pfree;
}
}
Node* InsertNode(Node* pList, int nPos, int nData)
{
if(NULL == pList) return NULL;
if(0 >= nPos)
{
pList = InsertHead(pList,nData);
return pList;
}
if(GetCount(pList) <= nPos)
{
pList = InsertTail(pList,nData);
return pList;
}
int nCount = 0;
Node* pCout = pList;
while(pCout->pNext != NULL)
{
nCount++;
if(nPos == nCount)
{
Node* pNew = new Node();
pNew->nData = nData;
pNew->pNext = pCout->pNext;
pCout->pNext = pNew;
return pList;
}
pCout = pCout->pNext;
}
nCount++;
}
Node* InsertTail(Node* pList, int nData)
{
if(NULL == pList) return NULL;
Node* pTail = pList;
while(pTail->pNext != NULL)
{
pTail = pTail->pNext;
}
Node* pNew = new Node();
pNew->nData = nData;
pNew->pNext = NULL;
pTail->pNext = pNew;
return pList;
}
Node* InsertHead(Node* pList, int nData)
{
if(NULL == pList) return NULL;
Node* pNew = new Node();
pNew->nData = nData;
pNew->pNext = pList;
pList = pNew;
return pList;
}
Node* CreateList(Node* pList, int nCount)
{
if(nCount <= 0) return NULL;
srand(GetTickCount());
if(pList == NULL)
{
pList = new Node();
pList->nData = ::rand();
}
nCount--;
Node* pNext = pList;
for(int i=0; i<nCount; i++)
{
Node* pTemp = new Node();
pTemp->nData = ::rand();
pNext->pNext = pTemp;
pNext = pNext->pNext;
}
return pList;
}
void CoutList(Node* pList)
{
if(NULL == pList)return;
Node* pCout = pList;
while(pCout->pNext != NULL)
{
cout<<pCout->nData<<endl;
pCout = pCout->pNext;
}
cout<<pCout->nData<<endl;
}
int GetCount(Node* pList)
{
if(NULL == pList)return 0;
int nCount = 0;
Node* pCout = pList;
while(pCout->pNext != NULL)
{
nCount++;
pCout = pCout->pNext;
}
nCount++;
return nCount;
}