我可以编写一个函数来创建新节点吗? [英] Can I write a function to create new nodes?

查看:118
本文介绍了我可以编写一个函数来创建新节点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想创建一个程序来创建值为1,2,3 ..,x的x节点然后打印它们的值,但我无法使它工作。它是否可能?



我尝试过:



< pre lang =c ++> #include < < span class =code-leadattribute> iostream >


class 节点
{

public

< span class =code-keyword> int val;
node * next;

};

void NewNode(节点* H, int i) // 我尝试使用& H但我的p-> next = H不起作用
{

node * p = new 节点;

p-> val = i;
p-> next = H;
H = p;

}

void DisplayNodes(节点* H)
{

node * p = new 节点;

p = H;


while (p!= NULL)
{

std :: cout << p-> val<< ;
p = p-> next;

}

}


int main()
{

节点* H = NULL;

int x;
std :: cin>> X;

std :: cout<< std :: endl<<的std :: ENDL;


for int i = 0 ; i< x; i ++)
{

NewNode(H,i);

}


DisplayNodes(H);


system( PAUSE);

}

解决方案

  void  NewNode(node * H, int  i) //  我尝试使用& H但我的p-> next = H不起作用 
{
node * p = 节点; // 确定

p-> val = i; // 确定
p-> next = H; // 确定
H = p; // 糟糕,您只需要更改本地参数变量H.
// 原文未更改。

}



最好这样做

  void  NewNode(节点* H, int  i) //  我尝试使用& H但我的p-> next = H不起作用 
{
node * p = new 节点;

p-> val = i;
p-> next = NULL;
H-> next = p; // 将新节点放在最后,而不是开头

}



您还需要更改 main 函数的逻辑。


So I wanted to make a program that creates x nodes with values 1,2,3..,x and then prints their values, but I can't make it work. Is it even possible?

What I have tried:

#include <iostream>


class node
{

public:

	int val;
	node * next;

};

void NewNode(node *H, int i) //I tried using &H but then my p->next=H doesn't work
{

	node *p = new node;

	p->val = i;
	p->next = H;
	H = p;

}

void DisplayNodes(node *H)
{

	node *p = new node;

	p = H;


	while (p != NULL)
	{

		std::cout << p->val << " ";
		p = p->next;

	}

}


int main()
{

	node *H = NULL;

	int x;
	std::cin >> x;

	std::cout << std::endl << std::endl;


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

		NewNode(H, i);

	}


	DisplayNodes(H);


	system("PAUSE");

}

解决方案

void NewNode(node *H, int i) //I tried using &H but then my p->next=H doesn't work
{
	node *p = new node; // OK

	p->val = i; // OK
	p->next = H;  // OK
	H = p;  // Oops, you are only changing the local parameter variable H.
                // The original is unchanged.

}


It would be better to do

void NewNode(node *H, int i) //I tried using &H but then my p->next=H doesn't work
{
	node *p = new node;

	p->val = i;
	p->next = NULL;
	H->next = p; // put the new node at the end, rather than the beginning

}


You will also need a change to the logic of your main function.


这篇关于我可以编写一个函数来创建新节点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆