c - 在 C 中前向链接一个链表
问题描述
您好,这里是“新手 C”开发人员,我正在寻找一些帮助,将这个用 Pascal 编写的程序翻译成 C:
type T = ^list;
list=record
info: integer;
next: T;
end;
var
L,P: T; i,ui,n: integer;
begin
write('Enter number of elements in your list: '); readln(n);
writeln;
New(L); //Creating a node
P := L; //assining P as a pointer
i:= 1;
while (i <= n) do
begin
writeln('enter a number: '); readln(ui);
P^.info:= ui;
new (P^.next); // creat a second node and automaticaly chain it to the previous one which means
P^.next:= new created P
P:= P^.next;
i:= i + 1;
end;
P^.next:= nil;
P:= L;
writeln('your list looks like this: ');
while (P <> nil) do
begin
write(P^.info,' ');
P:= P^.next;
end;
readln;
end.
这是一个使用前向链接技术使用while循环创建链接列表的程序,这意味着它只创建一个节点并使用它来创建其他节点并在循环内自动链接它们。此代码在 C 中的等价物如下:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *prev,*head,*p;
int n,i;
printf ("number of elements:");
scanf("%d",&n);
head=NULL;
for(i=0;i<n;i++)
{
p=malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
if(head==NULL)
head=p;
else
prev->next=p;
prev=p;
}
return 0;
}
我的问题是我想在 C 中创建相同的代码,但是我找不到我之前提到的“自动链接”的解决方案,特别是我正在寻找一种在 C 中编写以下指令的方法:
new(P^.next);
该指令所做的基本上是创建另一个节点并将其链接到前一个节点,而不是创建一个临时节点然后自己编写链接代码,就像您在说:
P^.next:= new created node;
我可以更详细,我想知道如何在 C 中替换此代码:
if(head==NULL)
head=p;
else
prev->next=p;
prev=p;
并写一个简单的指令,如帕斯卡中的 on
新的(P^.下一个);
解决方案
我相当确定这一点:
if(head==NULL)
head=p;
else
prev->next=p;
prev=p;
与此不同:
new(P^.next);
但是如果你想要一个等价的new(P^.next);
,你可以malloc
用来分配内存:
p->next = malloc(sizeof(*p->next));
您应该确保检查返回的指针malloc
是否NULL
也是 :
if(!p->next)
{
perror("malloc()");
return EXIT_FAILURE;
}
推荐阅读
- sql - 唯一查询给了我重复的行
- java - 创建带有逗号的超链接的 CSV
- javascript - 为什么 TypeScript 不能识别所有导出的函数
- swift - WebRTC 问题-!WKWebView 的浏览器中不存在 navigator.mediaDevices
- javascript - 通过单击动态元素的按钮,在每个循环中取消隐藏相关数据
- notifications - 从通知导航组件打开时避免片段重新创建
- c# - Xamarins.Essentials 和 Xamarin.Forms DependencyService 有什么区别
- reactjs - React js-将值传递给其他形式并在类中使用
- php - 如何使用 jQuery 保存这个 PHP 下拉列表的值?
- audio - 如何让 AIML 机器人以声音响应?有没有办法让这个声音成为自定义声音?