构造函数是使用了默认数据域为0,默认指针域为NULL 

#include<iostream>
#include<cstdlib>//size_t
using namespace std;
//用结构体类型表示一个节点

class Node {
public:
	typedef double value_type;
	Node(const value_type& init_data = 0, Node* init_link = NULL) {//默认构造函数的数据域为0
		data_field = init_data;
		link_field = init_link;
	}
	void set_data(const value_type& value) {
		data_field = value;
	}
	void set_link(Node* link) {
		link_field = link;
	}
	value_type data() {
		return data_field;
	}
	Node* link() {
		return link_field;
	}
private:
	value_type data_field;
	Node* link_field;
};
Node* create_list(int num) {
	Node::value_type head_data;
	cin >> head_data;
	Node* head_ptr = new Node(head_data);//我的头节点是有东西的
	Node* pre_ptr = head_ptr;//定义一个前向节点为头节点,后面就通过这个指针连起来
	for (int i = 1; i < num; ++i) {
		Node::value_type temp;
		cin >> temp;
		Node* new_ptr = new Node(temp);
		pre_ptr->set_link(new_ptr);//将前一个指针指向新节点
		pre_ptr = new_ptr;//然后更新该节点
	}
	return head_ptr;
}
//输出链表
void display_list(Node* head_ptr) {
	Node* cursor = head_ptr;
	for (; cursor != NULL; cursor = cursor->link()) {
		cout << cursor->data()<<' ';
	}
	cout << endl;
}
int main() {
	int n = 5;
	Node* head_ptr = create_list(n);//输入1 2 3 4 5
	display_list(head_ptr);//1 2 3 4 5
        while(1);
}

解析:

首先创建头节点,输入头节点数据域,指针域由构造函数可知指向NULL,然后循环创建节点,通过pre_ptr连接所以节点即可

步骤一、pre_ptr指向头节点,创建新节点

通过节点类创建和打印链表

步骤二、通过pre_ptr连接节点:设置pre_ptr的指针域为新节点,然后更新pre_ptr

通过节点类创建和打印链表

步骤三、重复步骤二,知道创建的节点到达预设的num即可.

(完)

相关文章:

  • 2021-05-17
  • 2022-02-07
  • 2021-06-20
  • 2021-05-17
  • 2022-01-05
  • 2022-12-23
  • 2022-12-23
  • 2021-12-16
猜你喜欢
  • 2022-12-23
  • 2021-07-08
  • 2021-05-17
  • 2022-12-23
  • 2022-12-23
  • 2021-04-22
  • 2021-12-03
相关资源
相似解决方案