1.实现将两个带头结点的链表L1和L2进行连接,连接后的链表仍然使用原来的存储空间;结果为链表L2连接到L1的末尾。
思路:找到链表L1的尾节点,使其指针域指向下一个链表的头结点(同时将链表L2所占用的内存空间进行回收)。
合并之前:
合并之后:
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode;
//创建链表
LNode* Create(void)
{
LNode *Head, *current;
Head = current = (LNode *)malloc(sizeof(LNode));
Head->next = NULL;
ElemType d;
LNode *temp;
char s;
while (1)
{
temp = (LNode *)malloc(sizeof(LNode)); //为新节点分配内存空间
scanf("%d", &temp->data);
current->next = temp;
current = temp;
s = getchar(); //s用来接收是否是回车
if (s == '\n') { break; }
}
current->next = NULL; //最后尾指针为NULL
return Head;
}
//输出链表
void List(LNode *L)
{
LNode *p;
p = L->next; //
while (p != NULL)
{
printf("%2d", p->data);
p = p->next;
}
}
void Merge(LNode *&A, LNode *&B, LNode *&C)
{
LNode *p, *q, *current;
p = A->next;
q = B->next;
free(B);
C = A;
C->next = NULL;
current = C;
while (p != NULL && q != NULL)
{
if (p->data <= q->data)
{
current->next = p;
p = p->next;
current = current->next;
}
else
{
current->next = q;
q = q->next;
current = current->next;
}
}
current->next = NULL;
if (p != NULL)
{
current->next = p;
}
if (q != NULL)
{
current->next = q;
}
}
int main()
{
LNode *L1, *L2,*L3;
printf("请输入第1个链表:\n");
L1 = Create();
printf("\n请输入第2个链表:\n");
L2 = Create();
Merge(L1, L2, L3);
printf("合并后的链表为:\n");
List(L3);
system("pause");
return 0;
}