c语言的链式存储用法

c语言的链式存储用法


2024年1月8日发(作者:)

c语言的链式存储用法

在C语言中,链式存储结构通常用于表示线性表、栈、队列等数据结构。链式存储结构通过指针来连接各个节点,每个节点包含数据和指向下一个节点的指针。下面是一个简单的示例,演示如何使用链式存储结构实现一个简单的单向链表。

首先,我们需要定义一个结构体来表示链表中的节点,包含数据和指向下一个节点的指针。

```c

struct Node {

int data;

struct Node next;

};

```

接下来,我们可以定义一个函数来创建新的节点。

```c

struct Node createNode(int data) {

struct Node newNode = (struct Node)malloc(sizeof(struct Node));

if (newNode == NULL) {

printf("Memory allocation failed.n");

exit(1);

}

newNode->data = data;

newNode->next = NULL;

return newNode;

}

```

接下来,我们可以定义一个函数来插入新的节点到链表中。

```c

void insertNode(struct Node head, int data) {

struct Node newNode = createNode(data);

if (head == NULL) {

head = newNode;

return;

}

struct Node current = head;

while (current->next != NULL) {

current = current->next;

}

current->next = newNode;

}

```

最后,我们可以定义一个函数来遍历链表并打印节点的数据。

```c

void printList(struct Node head) {

while (head != NULL) {

printf("%d ", head->data);

head = head->next;

}

printf("n");

}

```

现在,我们可以使用这些函数来创建一个简单的单向链表。例如:

```c

int main() {

struct Node head = NULL; // 初始时链表为空

insertNode(&head, 1); // 插入节点1到链表头部

insertNode(&head, 2); // 插入节点2到链表头部

insertNode(&head, 3); // 插入节点3到链表头部

printList(head); // 打印链表中的数据:3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 ... (后面还有很多) ... -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ... (后面还有很多) ... ) ... (这里显示了很多未初始化的数据,这是因为在malloc中为Node分配了内存但未初始化) ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...

... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...


发布者:admin,转转请注明出处:http://www.yc00.com/news/1704682997a1362475.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信