创建带有头结点(哑元节点)的链表的好处是可以将链表指针(head)作为参数传给函数,使函数可修改链表;使用头结点可以使函数接收或返回一个空表
link.h
//带有头结点的链表的建立
#include<iostream>
using namespace std;
struct listnode;
typedef struct listnode *link;
struct listnode
{
int element;
link next;
};
link Init_Link();//初始化链表
int IsEmpty_Link(link );//判断链表是否为空
void MakeEmpty_Link(link);//链表置空,释放内存
void InsertNode_link(link ,int );//插入结点
void DeleteNode_link(link,int );//删除结点
int FindNode_Link(link,int );//查找结点
void Print_link(link);//打印链表
link.cpp
#include "link.h"
#include<stdlib.h>
link Init_Link()//初始化带有头结点的链表
{
link head=(link)malloc(sizeof(struct listnode));
if(head==NULL)
{
cout<<"insufficient memory!"<<endl;
exit(0);
}
head->next=NULL;
return head;
}
int IsEmpty_Link(link head )
{
return head->next==NULL;
}
void MakeEmpty_Link(link head)
{
/*link p;*/
//for(p=head->next;p!=NULL;p=p->next)//这里使用for循环不能完成内存释放工作
//{
// link tmp;
// tmp=p;
// free(tmp);
//}
link p=head->next;
while(p)
{
link tmp;
tmp=p;
p=p->next;//必须先指定后继结点,在对该结点进行释放内存的工作
free(tmp);
}
head->next=NULL;
}
void InsertNode_link(link head ,int x )//保证按序插入
{
link newnode=(link)malloc(sizeof(struct listnode));
newnode->element =x;
//if(head->next==NULL)
//{
// head->next=newnode;
// newnode->next=NULL;
//}
// else
// {
link p;
link pre;
for(p=head->next,pre=head;p!=NULL;pre=p,p=p->next)
{
if(p->element > newnode->element)
{
break;
}
}
pre->next=newnode;
if(p==NULL)
newnode->next=NULL;
else
newnode->next=p;
// }
}
void DeleteNode_link(link head,int x)
{
link p,pre;
link tmp;
if(IsEmpty_Link(head))
{
cout<<"链表为空"<<endl;
exit(0);
}
if(!FindNode_Link(head,x))
{
cout<<"元素为x的节点没有找到,不能进行删除操作!"<<endl;
exit(0);
}
for(p=head->next,pre=head;p!=NULL;pre=p,p=p->next)
{
if(p->element==x)
break;
}
tmp=p;
pre->next=p->next;
free(tmp);
}
int FindNode_Link(link head,int x )
{
//虽然链表是有序的,但是这里不能折半查找方法
link p;
for(p=head->next;p!=NULL;p=p->next)
{
if(p->element==x)
return 1;
}
if(p==NULL)
return 0;
}
void Print_link(link head)
{
link p;
for(p=head->next;p!=NULL;p=p->next)
{
cout<<p->element<<" ";
}
cout<<endl;
}
main.cpp
#include"link.h"
int main(void)
{
link head;
head=Init_Link();
if(IsEmpty_Link(head))
{
cout<<"now,the link is empty!"<<endl;
}
cout<<"then insert the element into the link..."<<endl;
InsertNode_link(head,3);
InsertNode_link(head,2);
InsertNode_link(head,1);
Print_link(head);
MakeEmpty_Link( head);
InsertNode_link(head,5);
InsertNode_link(head,4);
cout<<"print the link:"<<endl;
Print_link(head);
cout<<endl<<"now ,delete the node which element is 3"<<endl;
DeleteNode_link(head,3);
cout<<endl<<"print the link "<<endl;
Print_link(head);
return 0;
}