数组和链表的相互转换

链表初始化

typedef struct ListNode{
	int val;
	ListNode* next;
	ListNode() : val(0), next(nullptr) {}
	ListNode(int x) : val(x), next(nullptr) {}
	ListNode(int x, ListNode* next) : val(x), next(next) {}
}*LinkList,ListNode;

创建链表

LinkList CreateList(const vector& nums) {
	ListNode* head = new ListNode;
	ListNode* cur = head;
	for(const int& i : nums) {
		ListNode* node = new ListNode(i);
		cur->next = node;
		cur = cur->next;
	}
	return head;
}

链表转数组

vector ListToNum(LinkList head) {
	vector num;
	ListNode* cur = head;
	while(cur->next != nullptr) {
		num.emplace_back(cur->next->val);
		cur = cur->next;
	}
	return num;
}

list

template
void Print(const list& my)
{
	typename list::const_iterator it = my.begin();
	for (; it != my.end(); it++)
	{
		cout << *it << "\t";
	}

	cout << endl;
}

你可能感兴趣的:(C++,STL,链表,数据结构)