2018/11/17 21:41
链表的基本操作 增删改查 有序链表的并集差集
#include<iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*Head;
void Init_List(LNode *L) //初始化
{
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;
}
void Create_List(LNode *L,int len)
{
int i;
LNode *p,*q;
p=L;
for(i=0;i<len;i++)
{
cout<<"输入第"<<i<<"值: ";
q = (LNode*)malloc(sizeof(LNode));
cin>>q->data;
p->next=q;
q->next=NULL;
p=p->next;
}
}
void Out_List(LNode *L) //输出
{
L=L->next;
if(!L)
cout<<"空的";
while(L)
{
cout<<L->data<<" ";
L=L->next;
}
cout<<endl;
}
void Insert_List(LNode *L,int e,int loc) //插入
{
LNode *q;
for(int i=0;i<loc;i++)
L=L->next;
q=(LNode*)malloc(sizeof(LNode));
q->data=e;
q->next=L->next;
L->next=q;
}
void Delete_List(LNode *L,int loc) //删除指定位置元素
{
int i;
LNode *p;
p=L;
for(i=0;i<loc-1;i++)
p=p->next;
if(p->next)
p->next=p->next->next;
else
p=NULL;
}
int Locate_List(LNode *L,int e) //根据元素查位置
{
int i = -1,j = 0;
while(L)
{
if(L->data==e)
i=j;
j++;
L=L->next;
}
if(i<0)
cout<<"查无此值!";
return i;
}
int Length_List(LNode *L) //求链表的长度
{
int i=0;
while(L->next!=NULL)
{
L=L->next;
i++;
}
return i;
}
void Combine_List(LNode *L1,LNode *L2) //L1UL2
{
struct LNode *p1,*p2,*t;
p1=L1;
p2=L2->next;
while(p1->next&&p2)
{
if(p1->next->data>p2->data)
{
t=p2->next;
p2->next=p1->next;
p1->next=p2;
p2=t;
}
else
p1=p1->next;
}
if(p2)
p1->next=p2;
}
LNode* Diff_List(LNode *L1,LNode *L2) //L1-L2
{
LNode * List1 =L1;
LNode * t1 = L1->next;
LNode * t2 =L2->next;
while(t1 && t2)
{
if(t2->data == t1->data)
{
t1=t1->next;
L1->next=t1;
}
else if(t2->data<t1->data)
{
t2 = t2->next;
L2 = L2->next;
}
else
{
t1 = t1->next;
L1=L1->next;
}
}
return List1;
}
int main()
{
LNode L1,L2;
int len,loc,e;
Init_List(&L1);
cout<<"请输入L1的长度:";
cin>>len;
Create_List(&L1,len);
cout<<"L1的值:";
Out_List(&L1);
Init_List(&L2);
cout<<"请输入L2的长度:";
cin>>len;
Create_List(&L2,len);
cout<<"L2的值:";
Out_List(&L2);
cout<<"输入要插入的值和下标:";
cin>>e>>loc;
Insert_List(&L1,e,loc);
Out_List(&L1);
cout<<"输入要删除的下位置:";
cin>>loc;
Delete_List(&L1,loc);
Out_List(&L1);
cout<<"输入要查找的值:";
cin>>e;
cout<<"位置为:"<<Locate_List(&L1,e)<<endl;
cout<<"L1UL1:";
Combine_List(&L1,&L2);
Out_List(&L1);
Diff_List(&L1,&L2);
cout<<"L1-L2:";
Out_List(&L1);
return 0;
}