#include<iostream>
using namespace std;
typedef struct LNode {
int data;//节点的数据域
struct LNode* next;//节点的指针域
}LNode, * LinkList;//LinkList为指向结构体LNode的指针类型
int InitList(LinkList& L)//初始化
{
L = new LNode;//生成新节点作为头节点,用头指针L指向头节点
L->next = NULL;//头节点的指针域置空
return 1;
}
int GetElem(LinkList L, int i, int& e)//取值
{
//在带头节点的单链表L中根据序号i获取元素的值,用e返回L中第i个数据元素的值
LinkList p = L->next;//初始化p,p指向首元节点
int j = 1;
while (p && j < i)
{
p = p->next;
++j;
}
if (!p || j > i)return 0;
e = p->data;//取第i个节点的数据域
return 1;
}
LNode* LocateElem(LinkList L, int e)//查找
{
LinkList p = L->next;//初始化,p指向首元节点
while (p && p->data != e)//顺链域向后查找,直到p为空或p所指节点的数据域等于e
p = p->next;//p指向下一节点
return p;//查找成功返回值为e的节点地址p,查找失败p为NULL
}
int ListInsert(LinkList& L, int i, int e)//插入
{//在带头节点的单链表L中第i个位置插入值为e的新节点
LinkList p = L; int j = 0;
while (p && (j < i - 1))
{
p = p->next; ++j;//查找第i-1个节点,p指向该节点
}
if (!p || j > i - 1)return -1;//i>n+1或者i<1
LNode* s = new LNode;//生成新节点*s
s->data = e;//将新节点*s的数据域置为e
s->next = p->next;//将节点*s的指针域指向节点ai
p->next = s;//将节点*s的指针域指向节点*s
return 1;
}
int ListDelete(LinkList& L, int i)
{
LinkList p = L; int j = 0;
while ((p->next) && (j < i - 1))//查找第i-1个节点,p指向该节点
{
p = p->next; ++j;
}
if (!(p->next) || (j > i - 1)) return 0;//当i>n或i<1时,删除位置不合理
LNode* q = p->next;//临时保存被删节点的地址以备释放
p->next = q->next;//改变删除节点前驱节点的指针域
delete q;//释放删除节点的空间
return 1;
}
void CreatList_H(LinkList& L, int n)//前插法
{
L = new LNode;
L->next = NULL;
for (int i = 0; i < n; i++)
{
LinkList p = new LNode;
cin >> p->data;
p->next = L->next;
L->next = p;
}
}
void CreatList_R(LinkList& L, int n)//后插法
{
L = new LNode;
L->next = NULL;
LinkList r = L;
for (int i = 0; i < n; i++)
{
LinkList p = new LNode;
cin >> p->data;
p->next = NULL; r->next = p;
r = p;
}
}
void PrintLinkList(LinkList& L)
{
LNode* p = L->next;
cout << "链表中的元素依次为:";
while (p)
{
cout << p->data << " ";
p = p->next;
}
}
void Merge_LinkList(LinkList& a, LinkList& b, LinkList& c)
{
LinkList pa = a->next;
LinkList pb = b->next;
c = a;
LinkList pc = c;
while (pa && pb)
{
if (pa->data < pb->data)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
else if (pa->data > pb->data)
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
else if (pa->data = pb->data)
{
pc->next = pa;
pc = pa;
pa = pa->next;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
delete b;
}
int main()
{
LinkList a;
cout << "请输入第一个按递减排列链表:" << endl;
CreatList_R(a, 5);
PrintLinkList(a); cout << endl;
int xy;
cout << "请输入你想插入的位置:";
cin >> xy;
int num;
cout << "你想插入的数字:";
cin >> num;
cout << "插入后";
ListInsert(a, xy, num);
PrintLinkList(a); cout << endl;
int ds;
cout << "请输入你想删除的位置:";
cin >> ds;
ListDelete(a, ds);
cout << "删除后";
PrintLinkList(a);
cout << endl;
int cm;
cout << "请输入你想查找的数字:";
cin >> cm;
cout << "该数字地址为" << LocateElem(a, cm) << endl;
LinkList b;
cout << "请输入第2个按递减排列链表:";
CreatList_R(b, 4);
LinkList c;
cout << "请输入第3个按递减排列链表:";
CreatList_R(c, 7);
LinkList d;
Merge_LinkList(b, c, d);
cout << "2 3链表合并的链表为:";
PrintLinkList(d);
}
运行结果: