python - 如何在 C 中创建链表结构

标签 python c struct linked-list

我正在尝试使用 Struct.C 语言创建 LinkedList 数据结构。下面我有两个例子,一个有效,一个无效。

首先,python 版本是我试图用 C (低于 python)重新创建的版本,是的,这是正在运行的代码的和平。我正在尝试让我的 C 版本正常工作,但我不确定它出了什么问题。有人可以尝试解决我的问题吗?甚至提供更好的解决方案?提前致谢!

Python版本

class Node:
    pass

start = Node()
point = start

point.val = 1
point.next = Node()
point = point.next

point.val = 2
point.next = Node()
point = point.next

point.val = 3
point.next = None

尝试使用 C

#include <stdio.h>

struct Node {
    struct Node *next;
    int val;
}; 

int main() {
    struct Node start;
    struct Node pointer = start;    
    int i;

    for (i = 0; i < 4; i++) {
        struct Node another;
        another.val = i;

        pointer.next = &another;

        pointer = *(pointer.next);      
    }   

    pointer = start;
    // Print out the value
    for (i = 0; i < 4; i++) {
        printf("%d\n", pointer.val);
        pointer = *(pointer.next);
    }

    return 0;
}

最佳答案

/* a linked list node */
typedef struct {
    int data;
    node *next;
} node;

/* represent a linked list as a pointer to the first node */
typedef node *list;

/* create a list by building first node */
list mklist(int firstData)
{
    node *n = malloc(sizeof(node));
    n->data = firstData;
    n->next = NULL;  /* the last node of the list always has next as NULL */
}
/* obtain a pointer to the tail node of a linked list */
node *getLast(list l)
{
    node *cur = l;
    while (cur->next != NULL)
        cur = cur->next;

    return cur;
}
/* add to the end of the linked list */
void append(list l, int newNodeData)
{
    node *last = getLast(l);

    last->next = malloc(sizeof(node));
    /* last->next represents our new node. We set its data to newNodeData,
       and since it is the last node, its next member is NULL */
    last->next->data = newNodeData;
    last->next->next = NULL;
}

关于python - 如何在 C 中创建链表结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48732705/

相关文章:

python线程和性能?

c - DBus:当名字从总线上消失时观察

C:解析输入文件以检查格式

c++ - 幻影类型是否与原始类型具有相同的对齐方式?

c - 成员之间不会有填充是否安全?

c++ - 检索 libevent 连接信息时“转发结构声明”

python - 如何将列表转换为字符串,然后在 python 中将其转换回?

python - 用零填充行,其他列有一些值,否则其他列没有值,在 python pandas 中用 NaN 填充它

python - 在 Python 中生成的单词

计算包含 1 的子集的数量