首页 > 解决方案 > 在 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^.下一个);

标签: clinked-list

解决方案


我相当确定这一点:

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;
}

推荐阅读