/*链表的创建与查找-2.8-插入-2.9-删除-2.10*/
#include<iostream>
using namespace std;
struct node
{
int date; //数据域
node *next; //指针域
};
int main()
{
int x=1;
node *head,*p; //定义头结点和节点
head= new node(); //动态分配头结点
p=head; //初始化节点
p->date=0; //指向头结点的数据 数据为0
p->next=NULL; //指向下一个节点的地址
while(x<7)
{
p->next=new node(); //动态分配节点
p=p->next; //指向下一个节点
p->date=x; //给节点赋值
++x;
}
p=head;
cout<<"List : ";
for(int i=0;i<x;++i) //输出链表
{
cout<<p->date<<",";
p=p->next;
}
cout<<endl;
cout<<"x= "<<x<<endl;
int d;
cout<<"请输入要查找的位置: ";
while(1){
cin>>d;
if(d>x)
continue;
else
break;
}
p=head;
for(int i=0;i<x;++i) //查找
{ if(i==d-1)
{ cout<<"第"<<d<<"位地址所保存的数据为:";cout<<p->date;break;}
p=p->next;
}
cout<<endl;
int b,a;
cout<<"请输入要插入的数";
cin>>b;
cout<<"请输入要插入的位置";
cin>>a;
node *s;
s=new node();
s->date=b;
p=head;
for(int i=0;i<x;++i) //插入
{ if(i==a-2)
{
s->next=p->next;
p->next=s;
break;
}
p=p->next;
}
p=head;
for(int i=0;i<x+1;++i)
{cout<<p->date<<",";
p=p->next;}
node *q;
cout<<endl<<"请输入你想删除的位置";
cin>>d;
p=head;
for(int i=0;i<x;++i) //删除
{ if(i==d-2)
{
q=p->next;
p->next=q->next;
delete q;
break;
}
p=p->next;
}
p=head;
for(int i=0;i<x;++i)
{cout<<p->date<<",";
p=p->next;}
while (1)
{
}
return 0;
}
/*头插法*/
#include<iostream>
int a,b;
using namespace std;
struct node
{
int date;
node *next;
};
class List
{
node *head;
public:
List() {head=NULL;}
void inser(int b);
void output();
};
void List:: inser(int b)
{
node *p,*s; //p指向链表节点的指针 s新增的节点
cout<<"请输入要插入的数据:";
cin>>b;
p=head;
s=new node(); //创建一个新的节点s
s->date=b;
s->next=NULL;
if(head==NULL) //如果没有节点 则插入的节点为头结点
head=s;
else
{
s->next=p; //把头结点作为新节点的下一个节点地址
head=s; //把新插入的节点作为头结点
}
}
void List::output()
{
node *p;
p=head;
cout<<"现在的链表为:";
while (p->next!=NULL)
{
cout<<p->date<<",";
p=p->next;
}
cout<<p->date<<endl;;
}
int main()
{
List L;
while (1)
{
L.inser(b);
L.output();
}
return 0;
}
/*尾插法*/
#include<iostream>
#define OK 1
#define ERROR 0
int a,b;
using namespace std;
struct node
{
int date;
node *next;
};
class List
{
node *head;
public:
List() {head=NULL;}
void inser(int b);
void output();
};
void List:: inser(int b)
{
node *p,*s; //p指向链表节点的指针 s新增的节点
cout<<"请输入要插入的数据:";
cin>>b;
p=head;
s=new node();
s->date=b;
s->next=NULL;
if(head==NULL)
head=s;
else
{
while(p->next!=NULL) //把指针移向最后一个节点
{
p=p->next;
}
p->next=s; //把新节点作为最后一个节点的下一个节点地址
}
}
void List::output()
{
node *p;
p=head;
cout<<"现在的链表为:";
while (p->next!=NULL)
{
cout<<p->date<<",";
p=p->next;
}
cout<<p->date<<endl;
}
int main()
{
List L;
while (1)
{
L.inser(b);
L.output();
}
return 0;
}