C++结构体构造函数,链表创建及其打印

以下例子的 head 头部,不用来保存有效数据

#include <iostream>
using namespace std;
 
struct ListNode {
    int val;
    ListNode *next;
};
//初始化列表
ListNode* InitList(ListNode *head, int n)
{
	int a=0;
	ListNode *p, *s;
	head = (ListNode*)malloc(sizeof(ListNode));
	head->next = nullptr;
	p=head;
	for (int i=0; i<n; i++)
	{
		s=(ListNode*)malloc(sizeof(ListNode));
		a=a+1;  //可以用输入的方式,这里是直接演示的自加
		s->val=a;
		s->next = nullptr;
		p->next = s;
		p=s;  
	}
	return head;
 } 
 //打印链表 
 void Print(ListNode *head)
 {
 	ListNode *p;
 	p=head->next;
 	while(p!=nullptr){
 		cout<<p->val;
 		p=p->next;
	 }
  } 
  //主函数
int main()
{
	ListNode *head;
	head = InitList(head, 5);
	Print(head);
	return 0;
}

结果

在这里插入图片描述

主要用到了动态申请内存,malloc(),以后在链表删除等还会用到free()等函数。

//初学者版本
struct ListNode {
    int val;
    ListNode *next;
};
//改进版本
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) {}

};

构造函数,结构体和类是类似的?

不再用molloc的方式,而是使用对象new一个的方式

//初学者
head = (ListNode*)malloc(sizeof(ListNode));
s=(ListNode*)malloc(sizeof(ListNode));
s->val=具体值;
s->next = nullptr;
//改进
head = new ListNode();  //调用无参构造函数ListNode() 
s = new ListNode(具体一个整数);  //调用了一个参数的构造函数 ListNode(int x)

代码,给了连个链表的具体值

#include <iostream>
using namespace std;

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) {}
};
//初始化列表
ListNode* InitList(ListNode *head, int *n, int length)
{
  int a=0;
  ListNode *p, *s;
  head = new ListNode();  //不是malloc()了
  p=head;
  
  for (int i=0; i<=length; i++)
  {
  	s = new ListNode(n[i]);  //不是malloc()了
  	p->next = s;
  	p=s;
  }
  return head;
} 
//打印链表 
void Print(ListNode *head)
{
  ListNode *p;
  p=head->next;
  while(p!=nullptr){
  	cout<<p->val;
  	p=p->next;
   }
  cout<<endl;
} 

int main()
{
  ListNode *l1,*l2;
  int a[]={2,4,3};  //链表节点具体值,这里就不一一输入,直接用数组来代替
  int b[]={5,6,4}; 
  l1 = InitList(l1, a, sizeof(a)/sizeof(a[0]));
  l2 = InitList(l2,b, sizeof(b)/sizeof(b[1]));
  Print(l2);
  Print(l1);
  return 0;
}

结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值