#include<iostream>
using namespace std;
struct Node{
int num;
Node* next;
};
int _tmain(int argc, _TCHAR* argv[])
{
/*
//有头结点
Node* phead = new Node;
Node head={0,NULL};
phead = &head;
Node* pNode;
bool bFirstNode = true;
//判断第一个结点或者其他的,头插法
for(int i=1;i<=5;i++)
{
Node* tempNode= new Node;
tempNode->num = i;
tempNode->next = NULL;
if (bFirstNode){
phead->next = tempNode;
bFirstNode = false;
}
else{
pNode = phead->next;
phead->next = tempNode;
tempNode->next = pNode;
}
}
//尾插法
Node* pLast = new Node;
for(int i=1;i<=5;i++)
{
Node* tempNode= new Node;
tempNode->num = i;
tempNode->next = NULL;
if (bFirstNode){
phead->next = tempNode;
pLast = tempNode;
bFirstNode = false;
}
else{
pLast->next = tempNode;
pLast = tempNode;
}
}
for(Node* pCurrent=phead->next;pCurrent!=NULL;pCurrent=pCurrent->next)
{
printf("%d\t",pCurrent->num);
}
*/
/*
//没有头结点的链表
Node* pHead = NULL;
//头插法
for(int i=1;i<=5;i++)
{
Node* tempNode= new Node;
tempNode->num = i;
tempNode->next = NULL;
Node* pTemp = pHead;
pHead = tempNode;
tempNode->next = pTemp;
}
Node* pHead = NULL;
Node* pLast = NULL;
bool bFirstNode = true;
//尾插法,需要判断是不是第一个元素
for(int i=1;i<=5;i++)
{
Node* tempNode= new Node;
tempNode->num = i;
tempNode->next = NULL;
if (bFirstNode)
{
pHead = pLast = tempNode;
bFirstNode = false;
}
else {
pLast->next = tempNode;
pLast = tempNode;
}
}
for(Node* pCurrent=pHead;pCurrent!=NULL;pCurrent=pCurrent->next)
{
printf("%d\t",pCurrent->num);
}
getchar();
return 0;
}
其中包含带头结点的链表:头插法和尾插法
不带头结点的链表:头插法和尾插法