【C++】创建链表

1. 简单链表

#include <iostream>

using std::cout;
using std::endl;

struct node
{
	int data;
	node *next;
};

//明确是变量还是指针
int main()
{
	node *p1, *p2;
	p1 = (node *)malloc(sizeof(node));
	p2 = (node *)malloc(sizeof(node));
	
	p1->data = 10;
	p1->next = NULL;
	
	p2->data = 20;
	p2->next = p1;
}

结果
在这里插入图片描述

2.链表初始化,并且依次打印节点值

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

struct node
{
	int data;
	node *next;
};


int main()
{
	node *head; // 增加一个变量,记录头指针
	node *p1, *p2;
	int N, num;

	head = NULL;
	p1 = NULL;
	p2 = NULL;

	cout << "input a number:" << endl;
	cin >> N;

	cout << "&p1: " << &p1 << endl;

	for (int i = 0; i < N; i++) {

		cin >> num;
		p1 = (node *)malloc(sizeof(node));
		p1->data = num;

		if (head == 0){
			head = p1;
		}
		else {
			p2->next = p1;
		}

		p2 = p1;
	}

	p2->next = NULL;

	node *p;
	p = head;

	while (p != NULL) {
		cout << p->data << endl;
		p = p->next;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值