单向链表综合实例
#include<iostream.h>
#include<conio.h>
struct node
{
int data;
node *next;
};
node *insertdata(int n,node *head);
node *deletedata(int n,node *head);
node *finddata(int n,node *head);
void outputlist(node *head);
int main()
{
int n;
int num;
node *listhead=NULL;
cout<<"请输入节点数 ";
cin>>n;
cout<<"请输入"<<n<<"个整数: ";
for(int i=0;i<n;i++)
{
cin>>num;
//将num按照从小到大的顺序插入链表中
listhead=insertdata(num,listhead);
}
outputlist(listhead);
cout<<"\n请输入需要查找的数: ";
cin>>num;
finddata(num,listhead);
//删除结点
cout<<"\n请输入想要删除的点: ";
cin>>num;
listhead=deletedata(num,listhead);
//输出删除结点后的链表
outputlist(listhead);
getch();
return 0;
}
//查找某数
node *finddata(int n,node *head)
{
node *curnode=head;
while(curnode)
{
if(curnode->data==n)
{
//找到n
cout<<"在列表中找到 "<<n<<endl;
return curnode;
}
curnode=curnode->next;
}
//未找到n
cout<<"没有找到 "<<n<<endl;
return NULL;
}
//插入某数(将输入的整数按找从小到大的顺序插入到已经排好序的链表中)
node *insertdata(int n,node *head)
{
node *curnode=head;
node *prenode=NULL;
node *newnode=NULL;
//找到插入位置
while((curnode!=0)&&(curnode->data<n)) //如果n最小,不用进入循环,直接插到表头前面
{
prenode=curnode; //在prenode后面插入结点
curnode=curnode->next; //在curnode前面插入结点
}
newnode=new node;
if(newnode==NULL)
{
cout<<"内存分配不成功 ";
return head;
}
//内存分配成功
newnode->data=n;
//插入位置为链表头,新建结点插入到链首结点之前
if(prenode==NULL)
{
newnode->next=head;
return newnode;
}
else
{
prenode->next=newnode;
newnode->next=curnode;
return head;
}
}
//删除结点
node *deletedata(int n,node *head)
{
node *curnode=head;
node *prenode=NULL;
if(head==NULL) //链表为空,直接返回
return NULL;
while((curnode!=NULL)&&(curnode->data!=n))
{
prenode=curnode; //prenode为要删除结点的前驱
curnode=curnode->next; //赋值符号左边的curnonde即为curnode->data==n时的结点指针
}
//未找到n
if(curnode==NULL)
{
cout<<"未在链表中找到 "<<n<<endl;
return head;
}
//删除的点为链首结点
if(prenode==NULL) //等价于if(curnode==head)
head=head->next;
else
prenode->next=curnode->next;
delete curnode;
return head;
}
//输出列表
void outputlist(node *head)
{
cout<<"List:";
node *curnode=head;
while(curnode)
{
cout<<curnode->data;
if(curnode->next)
cout<<"->";
curnode=curnode->next;
}
cout<<endl;
}