先放上运行截图哈!
上面的是头插法的运行结果,下面是尾插法的运行结果
下面是完整代码:
#include <iostream>
#include <stdio.h>
using namespace std;
/*链表结构体定义*/
typedef int ElemType;
struct List{
ElemType data;
struct List *next;
};
typedef struct List *list;
/*初始化无头结点单链表*/
bool f_initialize(list &L){
L=NULL;
return true;
}
/*判断无头结点链表是否为空*/
bool f_judge(list &L){
if(L==NULL){
return true;
}
else{
return false;
}
}
/*建立链表*/ //头插和尾插都需要头结点
/*头插法*/ //插入到头结点后面!!!
list f_headinsert(list &L){
L=(list)malloc(sizeof(List));
L->next=NULL;
ElemType x;
cout<<"\n输入节点数据,-1表示结束输入:\n";
cin>>x;
while(x!=-1){
list p=(list)malloc(sizeof(List));
p->data=x;
p->next=L->next; //注意p->next一定是L->next,不能是NULL,否则会丢失之前插入的节点
L->next=p;
cout<<"输入节点数据\n";
cin>>x;
}
return L;
}
/*尾插法*/
list f_endinsert(list &L){
L=(list)malloc(sizeof(List));
L->next=NULL;
list m=L;
ElemType x;
cout<<"\n输入节点数据,-1表示结束输入:\n";
cin>>x;
while(x!=-1){
list p=(list)malloc(sizeof(List));
p->data=x;
p->next=NULL; //注意p->next一定是L->next,不能是NULL,否则会丢失之前插入的节点
m->next=p;
m=p;
cout<<"输入节点数据\n";
cin>>x;
}
return L;
}
/*遍历链表*/
void fs_bl(list &L){
while(L->next!=NULL){
cout<<L->next->data<<"->";
L=L->next;
if(L->next==NULL){
cout<<"NULL";
}
}
}
/*主函数*/
int main()
{
list l;
f_initialize(l);
l=f_headinsert(l);
fs_bl(l);
l=f_endinsert(l);
fs_bl(l);
return 0;
}
希望对大家有用哦!