#include <iostream>
using namespace std;
#define OK (1)
#define ERROR (0)
typedef int Status;
typedef int ElemType;
int length = 0;//链表长度
typedef struct LNode {
ElemType data;
LNode* next;
} LNode;
//初始化空单链表
LNode* init()
{
LNode* head = new(LNode);//头指针
head->next = NULL;
head->data = 0;
length = 0;
return head;
}
//销毁
Status destroy(LNode* l)
{
LNode* q = NULL;
while (q)
{
q = l;
l = l->next;
delete q;
q = NULL;
}
return OK;
}
Status travel(LNode* l)
{
LNode* p = l->next;
while (p != NULL) {
cout << p->data;
if (p->next != NULL)
cout << "->";
p = p->next;
}
cout << endl;
return OK;
}
//插入
Status insert(LNode* l, int i, ElemType e)
{
LNode* p = new(LNode);
p->next = NULL;
p->data = e;
if (l->next == NULL)
{
l->next = p;
length++;
return OK;
}
else
{
LNode* q = l;
while (q->next)
{
q = q->next;
}
q->next = p;
length++;
}
return OK;
}
// 删除指定位置i的节点
Status remove(LNode* l, int i)
{
LNode* p = l, * q = l->next;
int j;
if (i == 0)
{
p->next = q->next;
delete q;
return OK;
}
for (j = 0; j < length; j++)
{
q = p;
p = p->next;
if (j == i)
{
q = p->next;
delete p;
return OK;
}
}
}
// 删除指定值为e的全部
Status removeKey(LNode* l, ElemType e)
{
LNode* p = l, * q = l;
while (p)
{
if (p->data == e)
{
q->next = p->next;
delete p;
return OK;
}
else
{
q = p;
p = p->next;
}
}
}
//根据x查找节点所在位置
int locate(LNode* l, ElemType x)
{
LNode* p = l;
for (int i = 0; i < length; i++)
{
p = p->next;
if (p->data == x)
{
return i + 1;
}
}
}
//根据位置i找到数据并存储至变量e
Status get(LNode* l, int i, ElemType& e)
{
LNode* p = l;
for (int j = 0; j < length; j++)
{
p = p->next;
if (j == i)
{
e = p->data;
return OK;
}
}
}
//合并连个有序链表
LNode* mergerTwoSortedList(LNode* head1, LNode* head2) {
LNode* head = new LNode();//head指针是每次后移的
LNode* firstNode = head;//需要确定好一个不变的头结点,然后返回这个头结点的next地址,才能返回完成的链表
while (head1 != NULL && head2 != NULL) {
if (head1->data > head2->data) {
head->next = head2;//这里只是确定好head->next是哪个结点,head还没有指向这个结点
head2 = head2->next;
}
else {
head->next = head1;
head1 = head1->next;
}
head = head->next;//head指向这个结点
}
head->next = head1 ? head1 : head2;//遇到一个为空后,哪个不为空就next指向哪一个
return firstNode->next;
}
int main()
{
//初始化
LNode* l = init();
LNode* z = init();
insert(l, 1, 1);
insert(l, 2, 3);
insert(l, 3, 5);
insert(l, 4, 7);
insert(l, 5, 9);
travel(l);
insert(z, 1, 2);
insert(z, 2, 4);
insert(z, 3, 6);
insert(z, 4, 8);
insert(z, 5, 10);
insert(z, 6, 12);
insert(z, 7, 13);
insert(z, 8, 14);
travel(z);
LNode* p = mergerTwoSortedList(l, z);//调用函数
p=p->next;
travel(p);
return 0;
}
两个有序单链表的合并
最新推荐文章于 2023-09-06 16:13:30 发布