数据结构 C++ 指针线性表的基本操作以及顺序合并

上一篇实现了数组线性表的基本操作和顺序合并,这篇实现一下指针线性表(单链表)

基本操作:插入、删除、定位

顺序合并:依旧是尾插法,假定原表已经排好序

#include <iostream>
#include <malloc.h>
using namespace std;

typedef int Elementtype;
struct celltype {
	Elementtype element;
	celltype *next;
};

typedef celltype *LIST;
typedef celltype *position;

position End(LIST L) {
	position q;
	q = L;
	while (q->next != NULL)
		q = q->next;
	return q;
}

void Insert(Elementtype x, position p) {
	position temp;
	temp = p->next;
	p->next = new celltype;
	p->next->element = x;
	p->next->next = temp;
}

void Delete(position p) {
	position q;
	if (p->next != NULL) {
		q = p->next;
		p->next = q->next;
		delete q;
	}
}

//定位
position Locate(Elementtype x, LIST L) {
	position p;
	p = L;
	while (p->next != NULL) {
		if (p->next->element == x)
			return p;
		else
			p = p->next;
	}
	return p;
}

position MakeNULL(LIST &L) {
	L = new celltype;
	L->next = NULL;
	return L;
}

LIST Mergetwo(LIST L1, LIST L2) {
	celltype *p = L1->next, *q = L2->next, *r, *s;
	LIST L3;
	L3 = (LIST)malloc(sizeof(celltype));
	r = L3;
	while (p != NULL && q != NULL) {
		if (p->element < q->element) {
			s = (celltype *)malloc(sizeof(celltype));
			s->element = p->element;
			r->next = s;
			r = s;
			p = p->next;
		} else {
			s = (celltype *)malloc(sizeof(celltype));
			s->element = q->element;
			r->next = s;
			r = s;
			q = q->next;
		}
	}
	while (p != NULL) {
		s = (celltype *)malloc(sizeof(celltype));
		s->element = p->element;
		r->next = s;
		r = s;
		p = p->next;
	}
	while (q != NULL) {
		s = (celltype *)malloc(sizeof(celltype));
		s->element = q->element;
		r->next = s;
		r = s;
		q = q->next;
	}
	r->next = NULL;
	return L3;
}

int main() {

	Elementtype a[5] = {1, 3, 5, 7, 9};
	Elementtype b[5] = {2, 4, 6, 8, 10};

	LIST L1, L2;
	L1 = (LIST)malloc(sizeof(celltype)); //初始化结点使用malloc函数,需要重点了解
	L2 = (LIST)malloc(sizeof(celltype));
	celltype *print1 = L1, *print2 = L2;
	celltype *s1, *r1 = L1;
	celltype *s2, *r2 = L2;

	for (int i = 0; i < 5; i++) {
		s1 = (celltype *)malloc(sizeof(celltype));
		s1->element = a[i];
		r1->next = s1;
		r1 = s1;
	}
	r1->next = NULL;

	for (int j = 0; j < 5; j++) {
		s2 = (celltype *)malloc(sizeof(celltype));
		s2->element = b[j];
		r2->next = s2;
		r2 = s2;
	}
	r2->next = NULL;

	cout << "LIST1" << endl;
	while (print1->next != NULL) {
		cout << print1->next->element << " ";
		print1 = print1->next;
	}

	cout << "\n" << "LIST2" << endl;
	while (print2->next != NULL) {
		cout << print2->next->element << " ";
		print2 = print2->next;
	}

	LIST L3;
	L3 = Mergetwo(L1, L2);
	cout << "\n" << "LIST3" << endl;
	while (L3->next != NULL) {
		cout << L3->next->element << " ";
		L3 = L3->next;
	}


	return 0;

}

主要参考:        《数据结构与算法》(第五版)张岩

                          《数据结构考研复习指导》(王道)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值