使用c++创建链表的一种方法

#include<iostream>
#include<vector>
using namespace std;

struct ListNode//定义节点,在c++中struct也是类。
{
	int val;
	ListNode *next;
ListNode(int x):val(x),next(NULL){}

};
class Solution
{
public:
	vector<int> Print(ListNode * L)
	{
		vector<int>v;
		if (L != NULL)
		{
			L = L->next;
			Print(L);
			v.push_back(L->val);
		}
		return v;
	}

};

int main()
{
//因为每个节点都是类,所以可以使用new来创建对象
	ListNode *Node1 = new ListNode(1);
	ListNode *Node2 = new ListNode(2);
	ListNode *Node3 = new ListNode(3);
	ListNode *Node4 = new ListNode(4);
	ListNode *Node5 = new ListNode(5);

//当然还有一种创建节点的方式:ListNode Node 而ListNode* Node是不行的,因为不存在这样的构造函数

	Node1->next = Node2;
	Node2->next = Node3;
	Node3->next = Node4;
	Node4->next = Node5;
	Node5->next = NULL;

	Solution st;
	st.Print(Node1);

	system("pause");
	return 0;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值