用c语言编写在带头结点的动态单链表和静态单链表上实现线性表操作LENGTH(L)的算法,并将长度写入头结点的数据域中
时间: 2024-05-09 20:20:24 浏览: 113
动态单链表实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct {
Node* head;
} LinkedList;
int LENGTH(LinkedList* L) {
int len = 0;
Node* p = L->head->next;
while (p != NULL) {
len++;
p = p->next;
}
L->head->data = len;
return len;
}
int main() {
LinkedList L;
L.head = (Node*)malloc(sizeof(Node));
L.head->data = 0; // 初始化头结点的数据域为0
L.head->next = NULL;
Node* p = L.head;
// 尾插法创建链表
for (int i = 1; i <= 5; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
p->next = node;
p = node;
}
printf("链表长度为:%d\n", LENGTH(&L));
printf("头结点的数据域为:%d\n", L.head->data);
return 0;
}
```
静态单链表实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data;
int next;
} Node;
typedef struct {
Node nodes[MAXSIZE];
int head;
} LinkedList;
int LENGTH(LinkedList* L) {
int len = 0;
int p = L->head;
while (p != -1) {
len++;
p = L->nodes[p].next;
}
L->nodes[0].data = len;
return len;
}
int main() {
LinkedList L;
L.head = 1;
// 初始化静态单链表
for (int i = 1; i < MAXSIZE; i++) {
L.nodes[i].next = i + 1;
}
L.nodes[MAXSIZE - 1].next = -1; // 最后一个结点的next为-1
L.nodes[0].data = 0; // 初始化头结点的数据域为0
int p = L.head;
// 尾插法创建链表
for (int i = 1; i <= 5; i++) {
L.nodes[p].data = i;
p = L.nodes[p].next;
}
printf("链表长度为:%d\n", LENGTH(&L));
printf("头结点的数据域为:%d\n", L.nodes[0].data);
return 0;
}
```
阅读全文