数据结构 C++单链表的复制

单链表的复制相对简单,另外代码中有生成单链表的两种方式,只是输入方式不一样,方法是一样的。

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

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

LIST Copy(LIST L1) {
	LIST L2;
	L2 = (LIST)malloc(sizeof(celltype));
	celltype *s, *r = L2, *p = L1->next;
	while (p != NULL) {
		s = (celltype *)malloc(sizeof(celltype));
		s->element = p->element;
		r->next = s;
		r = s;
		p = p->next;
	}
	r->next = NULL;

	return L2;
}

int main() {
	LIST L1;
	L1 = (LIST)malloc(sizeof(celltype));
	celltype *s1, *r1 = L1, *print1 = L1;

//	Elementtype a[5] = {1, 3, 5, 7, 9};
//	for (int i = 0; i < 5; i++) {
//		s1 = (celltype *)malloc(sizeof(celltype));
//		s1->element = a[i];
//		r1->next = s1;
//		r1 = s1;
//	}
//	r1->next = NULL;

	Elementtype x;
	cout << "Please input LIST1's element(Input -999 to exit):" << endl;
	cin >> x;
	while (x != -999) {
		s1 = (celltype *)malloc(sizeof(celltype));
		s1->element = x;
		r1->next = s1;
		r1 = s1;
		cin >> x;
	}
	r1->next = NULL;

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

	LIST L2;
	L2 = Copy(L1);
	celltype *print2 = L2->next;

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

	return 0;

}

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

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

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值