C语言结构体怎么生成一个双链表
时间: 2024-01-22 19:02:56 浏览: 73
c语言双链表实现
生成一个双链表需要定义一个结构体来表示链表中的每个节点,该结构体应该包含指向前一个节点和后一个节点的指针。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
char name[20];
int age;
char gender;
struct Node *prev;
struct Node *next;
};
struct Node *head = NULL;
struct Node *tail = NULL;
void addNode(char *name, int age, char gender) {
struct Node *newNode = (struct Node*) malloc(sizeof(struct Node));
strcpy(newNode->name, name);
newNode->age = age;
newNode->gender = gender;
newNode->prev = NULL;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
void printList() {
struct Node *current = head;
while (current != NULL) {
printf("Name: %s, Age: %d, Gender: %c\n", current->name, current->age, current->gender);
current = current->next;
}
}
int main() {
addNode("Alice", 25, 'F');
addNode("Bob", 30, 'M');
addNode("Charlie", 35, 'M');
addNode("David", 40, 'M');
printf("Forward:\n");
printList();
printf("\nBackward:\n");
struct Node *current = tail;
while (current != NULL) {
printf("Name: %s, Age: %d, Gender: %c\n", current->name, current->age, current->gender);
current = current->prev;
}
return 0;
}
```
该代码定义了一个名为Node的结构体,其中包含了指向前一个节点和后一个节点的指针。addNode函数用于向链表中添加新节点,printList函数用于打印链表中的所有节点。在main函数中,我们向链表中添加了四个节点,并分别打印了正向和反向的链表。
阅读全文