单链表:先进先出
#include<iostream>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
void CreateList(LinkList&L,int n){
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LNode* tail = new LNode();
tail = L;
for (int i = n;i>0;i--){
LinkList p = (LinkList)malloc(sizeof(LNode));
p->data = i;
tail->next = p;
tail =p;
tail->next=NULL;
}
}
void main(){
LinkList head;
LNode* tail = new LNode();
CreateList(head,5);
tail = head->next;
while (tail!=NULL)
{
cout<<tail->data<<endl;
tail = tail->next;
}
cout<<"hello"<<endl;
}
后进先出
#include<iostream>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
void CreateList(LinkList&L,int n){
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LNode* tail = new LNode();
tail = L;
for (int i = n;i>0;i--){
LinkList p = (LinkList)malloc(sizeof(LNode));
p->data = i;
p->next =tail->next;
tail->next = p;
}
}
void main(){
LinkList head;
LNode* tail = new LNode();
CreateList(head,5);
tail = head->next;
while (tail!=NULL)
{
cout<<tail->data<<endl;
tail = tail->next;
}
cout<<"hello"<<endl;
}
先进先出:先把带插入的节点指针放入tail的后面,之后让tail向后挪一位,使其指向刚刚插入的节点指针
后进先出:直接把带插入的节点指针的next指向头结点(tail)的next,直接从中间截断,造成后面是所有的数据(p->next =tail->next;)p后面挂载着所有的数据。然后令头结点(tail)指向p。从而连成一个完整的链表(tail->next = p;)