单链表习题
该解法并非最优,时间复杂度为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;
}
运行结果