C++使用数组构造链表

8 篇文章 1 订阅
4 篇文章 0 订阅

C++使用数组构造链表
1、链表的定义

struct Node{
	int value;
	struct Node* next;
};

2、使用数组构造链表

Node *createList_array(int *a, int n){
	Node *root = new Node();
	Node *pnode = root;
	
	for (int i = 0; i < n - 1; ++i){
		root->value = a[i];//当前节点
		root->next = NULL;

		Node *p = new Node();//下一个结点
		p->value = a[i + 1];
		p->next = NULL;

		root->next = p;// 连接 当前节点 与 下一个结点
		root = root->next;
	}
	root->next = NULL;//这一句 最重要!!
	return pnode;
}

3、显示链表的两种方法

void disp(Node* node){
	cout << "--------------------1" << endl;
	if (node == NULL)return;
	while (node != NULL){
		cout << node->value;
		if (node->next)	cout << "->";
		node = node->next;
	}
	cout << endl;
}

void disp2(Node* node){
	cout << "--------------------2" << endl;
	if (node == NULL)return;
	cout << node->value;
	while (node->next != NULL){
		cout << "->";
		node = node->next;
		cout << node->value;
	}
	cout << endl;
}

4、测试:

int main(){
	int a[] = { 1, 3, 5, 7, 9 };
	int n = sizeof(a) / sizeof(a[0]);
	Node *pnode = createList_array(a, n);
	disp(pnode);
	disp(pnode);

	disp2(pnode);
	disp2(pnode);
}

在这里插入图片描述

  • 1
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值