两种链表插入元素的方法,顺序与逆序。。。貌似有一种方法只适合建立动态链表时候使用。。。。
//2014-03-13-11.51
#include <iostream>
#include <cstdio>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
Node *head=NULL;
void make_list()
{
int n;
Node *p;
while(cin>>n)
{
p=new Node;
p->data=n;
p->next=head;
head=p;
}
cin.clear();
cin.sync();
}
void make_list2() //新结点始终在链表尾部
{
int n;Node *p,*q;
while(cin>>n)
{
p=new Node;
p->data=n;
p->next=NULL;
if(head==NULL)
head=p;
else q->next=p;
q=p;
}
p->next=NULL;
cin.clear();
cin.sync();
}
void out_list()
{
Node *ww=head;
while(ww!=NULL)
{
cout<<ww->data<<endl;
ww=ww->next;
}
}
void search(int x)
{
Node*h=head;
bool t=false;
while(h!=NULL)
{
if(h->data==x){t=true;break;}
h=h->next;
}
if(t)cout<<"存在。。"<<endl;
else cout<<"不存在。。。"<<endl;
}
void delete_first_node()
{
Node *t=head;
if(t)
{head=head->next;
delete t;}
else cout<<"空的,不能删除。。"<<endl;
}
void delete_node(int x)//这个和所给答案的方法很不同。。。
{
Node*t=head;
Node*p;
while(head->data==x)delete_first_node();
while(t!=NULL)
{
if(x==t->data)
{
Node *q=t;
p->next=t->next;
t=p;//上面这句很重要,当结尾有两个连续的结点需要删除时,必须有这个,让t复位。。。
delete q;
}
p=t;
t=t->next;
}
}
void make_list3()
{
int n;
Node *p,*q,*t;
while(cin>>n)
{
p=new Node;
p->data=n;
if(head==NULL||p->data<=head->data)//头结点为空或者头结点前插入
{
p->next=head;
head=p;
}
else
{
t=head;
int a=1;//开关,避免多次插入。。
while(t!=NULL)//遍历结点,在某结点前插入
{
if(p->data<=t->data&&a)
{
a=0;
// cout<<"进入这里。"<<endl;
q->next=p;
p->next=t;
}
q=t;
t=t->next;
}
if(p->data>q->data)//如果大于所有的结点,循环后插入
{
q->next=p;
p->next=NULL;
}
}
}
cin.clear();
cin.sync();
}
void insert(int n)//基本和上一个一样
{
Node *p,*q,*t;
// while(cin>>n)
// {
p=new Node;
p->data=n;
if(head==NULL||p->data<=head->data)//头结点为空或者头结点前插入
{
p->next=head;
head=p;
}
else
{
t=head;
int a=1;//开关,避免多次插入。。
while(t!=NULL)//遍历结点,在某结点前插入
{
if(p->data<=t->data&&a)
{
a=0;
// cout<<"进入这里。"<<endl;
q->next=p;
p->next=t;
}
q=t;
t=t->next;
}
if(p->data>q->data)//如果大于所有的结点,循环后插入
{
q->next=p;
p->next=NULL;
}
}
// }
cin.clear();
cin.sync();
}
int main( )
{
// freopen("input.txt","r",stdin);
// make_list2();
// out_list();
// make_list();
make_list3();
out_list();
cout<<"插入5后:"<<endl;
insert(5);
out_list();
// search(5);
// cout<<"去掉第一点后:"<<endl;
// delete_first_node();
// out_list();
// cout<<"删除56结点:"<<endl;
// delete_node(56);
// out_list();
return 0;
}
//2014-03-14-14.16