我正在尝试使用 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/