admin 管理员组

文章数量: 1087135


2024年5月20日发(作者:osi七层模型低三层是)

c语言链表代码

以下是一个简单的双向链表的C语言代码:

#include

#include

struct Node {

int data;

struct Node* prev;

struct Node* next;

};

struct Node* head;

创建链表

void createList(int n){

struct Node* newNode;

struct Node* temp;

int data, i;

head = (struct Node*)malloc(sizeof(struct Node));

if (head == NULL) {

printf("Memory cannot be allocated.");

}

else {

printf("Enter the data of node 1: ");

scanf("%d", &data);

head->data = data;

head->prev = NULL;

head->next = NULL;

temp = head;

for(i=2; i<=n; i++) {

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

if (newNode == NULL) {

printf("Memory cannot be allocated.");

break;

}

else {

printf("Enter the data of node %d: ", i);

scanf("%d", &data);

newNode->data = data;

newNode->prev = temp;

newNode->next = NULL;

temp->next = newNode;

temp = temp->next;

}

}

}

}

遍历链表

void traverseList() {

struct Node* temp;

if (head == NULL) {

printf("List is empty");

}

else {

temp = head;

while (temp != NULL) {

printf("Data = %dn", temp->data);

temp = temp->next;

}

}

}

int main() {

int n;

printf("Enter the total number of nodes: ");

scanf("%d", &n);

createList(n);

printf("nData entered in the list:n");

traverseList();

return 0;

}

此代码中的struct Node数据结构包含三个成员变量:

- data:节点的数据

- prev:指向节点前一个节点的指针

- next:指向节点后一个节点的指针

在createList函数中,为了方便,我们将第一个节点作为头节点。因此,我们为

头节点分配内存,并将prev和next指针都设置为NULL。随后,我们提示用户

输入第一个节点的数据。然后,我们使用一个循环来创建剩余的节点,并逐个将

它们连接起来。最后,我们在主函数中调用createList和traverseList函数来创

建和遍历链表。


本文标签: 节点 链表 代码 创建 数据结构