【发布时间】:2021-12-26 10:24:13
【问题描述】:
我没有得到 create_node() 函数中的 else 部分..
正如您在 else 部分中看到的那样,为 r 分配了内存块,并分配了 coeff 和 power...但是他们什么时候将 r 节点分配给链表的最后一个.. 他们什么时候遍历到链表的末尾
我的意思是它是如何在链表的最后分配的。
#include <bits/stdc++.h>
using namespace std;
struct Node {
int coeff;
int pow;
struct Node* next;
};
// Function to create new node
void create_node(int x, int y, struct Node** temp)
{
struct Node *r, *z;
z = *temp;
if (z == NULL) {
r = (struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
else {
r->coeff = x;
r->pow = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}
// Display Linked list
void show(struct Node* node)
{
while (node->next != NULL) {
printf("%dx^%d", node->coeff, node->pow);
node = node->next;
if (node->coeff >= 0) {
if (node->next != NULL)
printf("+");
}
}
}
// Driver code
int main()
{
struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
// Create first list of 5x^2 + 4x^1 + 2x^0
create_node(5, 2, &poly1);
create_node(4, 1, &poly1);
create_node(2, 0, &poly1);
// Create second list of -5x^1 - 5x^0
create_node(-5, 2, &poly2);
create_node(-5, 0, &poly2);
printf("1st Number: ");
show(poly1);
printf("\n2nd Number: ");
show(poly2);
return 0;
}
只有我认为 create_node() 函数应该比上面的代码更像这样吗?
void create_node(int x, int y, struct Node** temp)
{
struct Node *r, *z;
z = *temp;
if (z == NULL) {
r = (struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
r->next=NULL;
*temp = r;
}
else {
r = (struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
r->next=NULL;
while(z->next!=NULL)
{
z=z->next;
}
z->next=r;
}
}
我真的很想知道它如何产生正确的输出,即使没有将 newnode 分配给链表的最后一个
【问题讨论】:
-
我们需要召集一个理事会来确定你是否是唯一一个这样认为的人。
-
首先这不是 C++ 而是 C,所以这里的标签可能会产生误导。其次,链表的要点是您可以以相同的成本插入/前置/附加到它。
create_node接受一个节点并附加到它。else分支用于当作为temp传入的节点不是最后一个也称为tail(或者更确切地说它根据此实现存在)时。
标签: c++ struct linked-list singly-linked-list