#include<iostream>
#include<vector>
using namespace std;
int n;
#define num b
class student//定义链表的结构
{
public:
int b;
student * next;
};
student* creat()//输入函数
{
student *head,*p1,*p2;
n=0;
head=nullptr;
p1=p2=new student;
cin>>(*p1).b;
while((*p1).b!=0)//当链表内容不为0时
{
n=n+1; //若结点赋值成功,则链表结点数加一
if(n==1)
head=p1;//结点数为一时让头指针指向p1
else
(*p2).next=p1;//链接
p2=p1;//把p1空出来,继续创建结点
p1=new student;//p1开辟新的结点
cin>>(*p1).b;
}
(*p2).next=nullptr;
return(head);
}
void print(student* head)//打印链表
{
student*p;
p=head;
while(p!=nullptr)
{
cout<<(*p).b<<'\n';
p=p->next;
}
}
student* del(student* head,int b)
{
student *p1,*p2;
if(head==nullptr)
{
cout<<"list is null\n";
return nullptr;
}//如果链表为空
p1=head;
while(p1->num!=num && p1->next!=nullptr)
{
p2=p1;p1=p1->next;
}//当p1指向的结点不是要删除的结点,且链表没有遍历完
if(p1->num==num)
{
if(num==head->num)
head=p1->next;//若要删除的结点是第一个结点,把head往后移
else
p2->next=p1->next;
delete p1;
n=n-1;//总结点个数
return head;
}
cout<<"no found the number"<<'\n';
return head;
}
student*insert(student* p1,student*head,int num,int direction)//插入结点
{
enum {front,back};//枚举变量确定插入位置
student*p2;
p2=head;
if(head==nullptr)//链表为空
head=p1;
else if(head->num==num && direction==front)//若插入的位置在第一个结点前面
{
p1->next=head;
head=p1;
}
else
while (p2->next != nullptr)//链表位遍历到末尾
{
if((p2->next)->num==num)//p2作为插入的定位结点的前一个结点
{
switch (direction)//插入到前还是后
{
case front:
{
p1->next=p2->next;
p2->next=p1;
break;
}
case back:
{
p1->next=(p2->next)->next;
(p2->next)->next=p1;
break;
}
default:break;
}
return head;
}
p2=p2->next;//结点后移
}
cout<<"there is no match"<<endl;//遍历结束后没有找到匹配项
return head;
}
int main()
{
student *head,stu;
int del_num;
int num,direction,a=100;
cout<<"Please input the list,when you want to end it,input the 0:"<<endl;
head=creat();//创建链表
cout<<"then we will output the list"<<endl;
print(head);
cout<<"Input the deleted number.If you want to end,input a char\n";
while(cin>>del_num)
head=del(head,del_num);//要删除的数
cin.clear();//重置输入流状态
cin.ignore();//清空输入流,防止影响到后续的while判断
cout<<"Then we will output the list after being deleted\n";
print(head);
cout<<"please input the number of numbers you want to insert:"<<endl;
cin>>a;
cout<<"Input the inserted record ,the search condition and the direction you want(0 means front,1 means back):\n";
for(int i=0;i<a;i++)
{ cin>>stu.num>>num>>direction;
head=insert(&stu,head,num,direction);
}//插入的数据,定位条件和前后位置
cout<<"The list after insertion is complete:\n";
print(head);
return 0;
}
包括了动态链表的输入,删除结点函数及插入结点函数。
连续插入太麻烦了,各种莫名其妙的问题。
while里面的第一个处理对象永远自动赋0
还有相同数的插入会不断循环。
bug以后再解决