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函数来创
建和遍历链表。
版权声明:本文标题:c语言链表代码 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/b/1716213311a692165.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论