在 C 中显示带有链表的多项式

如何解决在 C 中显示带有链表的多项式

我正在尝试编写创建和显示多项式的代码。我的第一个问题是:“我是否正确使用了链表?”。其次是:“为什么我不能显示多项式?”我希望它们显示为:如果有 2 个单项式,多项式应显示为; -->(1.0 X 0) -->(1.0 X 3)--E 第一个是系数,第二个是指数。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//this will be the structure named node
struct node
{
    int exp;           //this line represents the exponent/power b for a*x^b
    int coeff;         //this line represents the coefficient a for a*x^b
    struct node *next; //this line represents the pointer which will point to the next node
};
struct node *create_new_nodes(struct node *m);
struct node *insert(struct node *ptr,struct node *k);
void display(char const *tag,struct node *ptr);

struct node *create_new_nodes(struct node *m)
{
    int i;
    int n;
    printf("Enter the number of nodes: ");
    scanf("%d",&n);
    for (i = 0; i < n; i++)
    {
        struct node *ptr = malloc(sizeof(struct node));
        printf("Enter the coefficient (a for a*x^b): ");
        scanf("%d",&ptr->coeff);
        printf("Enter the exponent/power (b for a*x^b): ");
        scanf("%d",&ptr->exp);
        ptr->next = NULL;
    }
    return m;
}

void display(char const *tag,struct node *ptr)
{
    struct node *temp;    
    temp = ptr;
    printf("%s: ",tag);
    while (temp != NULL)
    {
        printf("-->(%d X %d)--E",temp->coeff,temp->exp);
        temp = temp->next;
    }
    putchar('\n');
}

int main(void)
{
    struct node *p1 = NULL,*p2 = NULL;

    p1 = create_new_nodes(p1);

    p2 = create_new_nodes(p2);

    display("p1",p1);
    display("p2",p2);

    return 0;
}

我对这段代码的输出:

Enter the number of nodes: 2
Enter the coefficient (a for a*x^b): 1
Enter the exponent/power (b for a*x^b): 2
Enter the coefficient (a for a*x^b): 2
Enter the exponent/power (b for a*x^b): 3
Enter the number of nodes: 2
Enter the coefficient (a for a*x^b): 3
Enter the exponent/power (b for a*x^b): 4
Enter the coefficient (a for a*x^b): 6
Enter the exponent/power (b for a*x^b): 5
p1: 
p2: 

如您所见,未显示 p1 和 p2。

我不得不提一下,我在编写此代码的某些部分时从互联网上获得了帮助。所以,有些部分我不明白。如果可能的话,我也想澄清一下。

void display(char const *tag,struct node *ptr)
{
    struct node *temp;
    const char *pad;

    temp = ptr;
    printf("%s: ",temp->exp);
        temp = temp->next;
        pad = " + ";
    }
    putchar('\n');
}

在这部分代码中,我不明白为什么要使用 temp 和 tag 功能。

解决方法

让我们帮你解决。您只需要创建、显示和删除函数,而不是完整的通用链表实现。由于您的列表只是带有 expcoeff 的结构链接,因此您可以在每次调用 create 函数时简单地构建一个新列表。您不需要为 create 函数提供参数,只需声明函数本地的列表指针,然后在完成后返回指向已分配列表中第一个节点的指针。

正如评论中所指出的,除非您检查每个使用的输入函数的返回(没有提到,但同样重要,检查每个分配的回报)

您与创建函数的目标相去甚远,只是您从未将列表中的节点链接在一起。您确实希望在分配后初始化 next 指针 NULL,但您还必须将列表中的任何现有结束节点 next 指针设置为指向新节点。这就是您在“链表​​”中创建“链接”的方式。

让我们使用您的 create 函数,(我已将其重命名为 create_poly_list())并且基本上您可以声明 headtail 列表指针到函数本地({{1} } 指针临时用于构建列表),然后在调用者(此处为tail)完成分配后返回head。所以你真正需要的只是声明你的列表指针,然后按顺序添加每个节点,例如

main()

然后在 struct node *head = NULL,*tail = NULL; /* temporary list pointers */ ... if (head == NULL) /* add first node */ head = tail = ptr; else { tail->next = ptr; /* set last node ->next to new node */ tail = ptr; /* update tail to new node */ } ... return head; /* return pointer to start of list */ 中,您只需为每个多项式调用 main(),例如

create_poly_list()

现在让我们整理一下,以便验证每个输入和分配,在输入或分配失败时返回 p1 = create_poly_list(); p2 = create_poly_list(); (并记住 NULL 所有内存,如果在失败之前分配了内存,以防止出现错误内存泄漏),例如

free()

您的 struct node *create_poly_list (void) /* no parameter required */ { int i,n; struct node *head = NULL,*tail = NULL; /* temporary list pointers */ fputs ("\nEnter the number of nodes: ",stdout); if (scanf("%d",&n) != 1) return NULL; for (i = 0; i < n; i++) { struct node *ptr = malloc (sizeof *ptr); if (!ptr) { /* validate EVERY allocation */ while (head) { /* if nodes in list */ struct node *victim = head; /* free all nodes (or leak) */ head = head->next; free (victim); } return NULL; /* now return NULL on error */ } ptr->next = NULL; /* initialize next ptr NULL */ fputs ("\nEnter the coefficient (a for a*x^b) : ",stdout); if (scanf ("%d",&ptr->coeff) != 1) { fputs ("error: invalid integer input.\n",stderr); /* you would likewise need to free prior nodes here */ return NULL; } fputs ("Enter the exponent/power (b for a*x^b): ",stdout); if (scanf("%d",&ptr->exp) != 1) { fputs ("error: invalid integer input.\n",stderr); /* you would likewise need to free prior nodes here */ return NULL; } if (head == NULL) /* add first node */ head = tail = ptr; else { tail->next = ptr; /* set last node ->next to new node */ tail = ptr; /* update tail to new node */ } } return head; /* return pointer to start of list */ } 函数很好,但您应该检查 display() 是否为 ptr(例如列表为空)以通知用户列表状态,以防尝试显示一个空列表,例如

NULL

这里你需要在完成每个列表后释放它的内存。 (是的,内存将在程序退出时被释放,但大概您不会总是编写在 void display (char const *tag,struct node *ptr) { if (!ptr) { /* validate list not NULL */ puts ("(list-empty)"); return; } struct node *temp = ptr; printf("%s: ",tag); while (temp) { printf("-->(%d X %d)--E",temp->coeff,temp->exp); temp = temp->next; } putchar('\n'); } 中创建所有列表的简单程序)。尽早建立良好的内存管理习惯。您只需要一个简单的删除列表功能,例如

main()

总而言之,你会:

void del_list (struct node *list)
{
    while (list) {
        struct node *victim = list;
        list = list->next;
        free (victim);
    }
}

注意:为什么要包含 #include <stdio.h> #include <stdlib.h> struct node { int exp; int coeff; struct node *next; }; struct node *create_poly_list (void) /* no parameter required */ { int i,stderr); /* you would likewise need to free prior nodes here */ return NULL; } if (head == NULL) /* add first node */ head = tail = ptr; else { tail->next = ptr; /* set last node ->next to new node */ tail = ptr; /* update tail to new node */ } } return head; /* return pointer to start of list */ } void display (char const *tag,temp->exp); temp = temp->next; } putchar('\n'); } void del_list (struct node *list) { while (list) { struct node *victim = list; list = list->next; free (victim); } } int main(void) { struct node *p1 = NULL,*p2 = NULL; p1 = create_poly_list(); p2 = create_poly_list(); putchar ('\n'); display("p1",p1); display("p2",p2); del_list (p1); del_list (p2); return 0; } 有点令人困惑...)

示例使用/输出

string.h

内存使用/错误检查

在您编写的任何动态分配内存的代码中,对于分配的任何内存块,您有 2 个责任:(1) 始终保留一个指向起始地址的指针内存块,(2) 可以在不再需要时释放

您必须使用内存错误检查程序来确保您不会尝试访问内存或超出/超出分配块的范围进行写入,尝试读取或基于未初始化值的条件跳转,最后,以确认您释放了所有分配的内存。

对于 Linux $ ./bin/poly_list Enter the number of nodes: 2 Enter the coefficient (a for a*x^b) : 2 Enter the exponent/power (b for a*x^b): 6 Enter the coefficient (a for a*x^b) : 3 Enter the exponent/power (b for a*x^b): 7 Enter the number of nodes: 3 Enter the coefficient (a for a*x^b) : 1 Enter the exponent/power (b for a*x^b): 3 Enter the coefficient (a for a*x^b) : 3 Enter the exponent/power (b for a*x^b): 5 Enter the coefficient (a for a*x^b) : 5 Enter the exponent/power (b for a*x^b): 7 p1: -->(2 X 6)--E-->(3 X 7)--E p2: -->(1 X 3)--E-->(3 X 5)--E-->(5 X 7)--E 是正常选择。每个平台都有类似的内存检查器。它们都易于使用,只需通过它运行您的程序即可。

valgrind

始终确认您已释放分配的所有内存,并且没有内存错误。

检查一下,如果您还有其他问题,请告诉我。

,

我可能错了,但在函数中

struct node *create_new_nodes(struct node *m)

看起来返回类型和参数都是指针。真的,你回来了

struct node **m

不确定这是否是错误的,但如果是,则在您执行此操作时可能会出现相同的问题

printf("-->(%d X %d)--E",temp->exp);

tempptr 时,即为 struct node*。所以你说的是(**node).coeff。但这只是我累了的观察,如果有用就忽略我。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res