连接两个单链表的一种解法

单链表习题
该解法并非最优,时间复杂度为O(n)。
test.h

#ifndef TEST_H_
#define TEST_H_
#include<malloc.h>

typedef int ElemType;
typedef struct Node
{
	ElemType data;
	struct Node * next;
}Node;
typedef struct Node * Linklist;
//利用尾插法创建线性表整表
Linklist createOneList(const int *a, const int length);
//连接两个链表
void cennectList(Linklist L1,Linklist L2);
#endif // !TEST_H_
#pragma once

test.cpp

#include"test.h"

//利用尾插法创建线性表整表
Linklist createOneList(const int *a, const int length) {

	Linklist L = (Linklist)malloc(sizeof(Node));
	Linklist r = L;//头节点
	Linklist s = nullptr;
	for (int i = 0; i < length; i++)
	{
		s = (Linklist)malloc(sizeof(Linklist));
		s->data = a[i];
		r->next = s;
		r = s;
	}
	r->next = nullptr;
	return L;
}

void cennectList(Linklist L1,Linklist L2) {

	Linklist r = L1;
	
	while (r->next != nullptr)
	{
		r = r->next;
	}
	r->next = L2->next;
	free(L2);
}

main.cpp

#include<iostream>
#include"test.h"
void showList(const Linklist L);
int main()
{
	int a[5] = { 1,2,3,4,5 };
	Linklist L1 = createOneList(a, 5);
	showList(L1);

	int b[5] = { 7,8,9,10,11 };
	Linklist L2 = createOneList(b, 5);
	showList(L2);
	cennectList(L1, L2);
	showList(L1);
	return 0;
}

void showList(const Linklist L) {

	Linklist p = L->next;
	while (p != nullptr)
	{
		std::cout << p->data << " ";
		p = p->next;
	}
	std::cout << std::endl;
}

运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值