954: 单链表的链接

文章介绍了使用C语言自定义链表结构以及如何在主函数中进行动态添加和合并操作,然后与C++STL中的vector进行性能对比。
摘要由CSDN通过智能技术生成

学习版

【c语言】

【C艹】

#include<iostream>

class LinkedList {
public:
	struct LinkedNode {
		char val;
		LinkedNode* next;
		LinkedNode(char val) :val(val), next(NULL) {};
	};
	LinkedList(){
		dummyHead = new LinkedNode('0');
		tail = dummyHead;
	}
	~LinkedList() {
		while (dummyHead) {
			LinkedNode* tmp = dummyHead;
			dummyHead = dummyHead->next;
			delete tmp;
		}
	}
	void addTail(char value) {
		LinkedNode* newNode = new LinkedNode(value);
		tail->next = newNode;
		tail = tail->next;
	}
	void appendList(LinkedList& list2) {
		LinkedNode* cur = list2.dummyHead;
		while (cur->next != NULL) {
			tail->next = cur->next;
			tail = tail->next;
			cur = cur->next;
		}
	}
	void printList() {
		LinkedNode* cur = dummyHead;
		while (cur->next != NULL) {
			std::cout << cur->next->val << " ";
			cur = cur->next;
		}
		exit(-1);
	}
private:
	LinkedNode* dummyHead;
	LinkedNode* tail;

};

int main() {

	LinkedList list1, list2;
	int n, m;
	char a;
	std::cin >> n;
	while (n--) {
		std::cin >> a;
		list1.addTail(a);
	}
	std::cin >> m;
	while (m--) {
		std::cin >> a;
		list2.addTail(a);
	}
	list1.appendList(list2);
	list1.printList();
	return 0;
}

【STL】

#include<iostream>
#include<vector>

int main() {
	int n, m;
	std::cin >> n;
	std::vector<char> list1(n);
	for (int i = 0; i < n; i++) std::cin >> list1[i];
	std::cin >> m;
	std::vector<char> list2(m);
	for (int i = 0; i < m; i++) std::cin >> list2[i];
	list1.insert(list1.end(), list2.begin(), list2.end());
	for (int i = 0; i < list1.size(); i++)
		std::cout << list1[i] << " ";
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值