将一个已知数组写入链表,用于测试算法

#include<iostream>
#define N 5
using namespace std;
struct mylist
{
	int val;
	mylist*next;
};
mylist *newlist(int a[])
{
	mylist*head, *node, *cur;
	head = node = new mylist;
	node->val = a[0];
	for (int i = 1; i < N; i++)
	{
		cur = new mylist;
		cur->val = a[i];
		cur->next = nullptr;
		node->next = cur;
		node = cur;
	}
	return head;
}
int main()
{
	int a[N] = { 1,2,3,4,5 };
	mylist *head;
	head = newlist(a);
	while (head != nullptr)
	{
		cout << head->val << endl;
		head = head->next;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40736096/article/details/79586941
今日推荐