写一个程序实现单链表的ADT
时间: 2023-05-12 19:03:00 浏览: 107
好的,以下是一个实现单链表的ADT的程序示例:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct List {
Node *head;
int size;
} List;
List *createList() {
List *list = (List*)malloc(sizeof(List));
list->head = NULL;
list->size = 0;
return list;
}
void add(List *list, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
} else {
Node *current = list->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
list->size++;
}
void removeAt(List *list, int index) {
if (index < 0 || index >= list->size) {
printf("Invalid index\n");
return;
}
Node *current = list->head;
if (index == 0) {
list->head = current->next;
free(current);
} else {
Node *prev = NULL;
int i;
for (i = 0; i < index; i++) {
prev = current;
current = current->next;
}
prev->next = current->next;
free(current);
}
list->size--;
}
int get(List *list, int index) {
if (index < 0 || index >= list->size) {
printf("Invalid index\n");
return -1;
}
Node *current = list->head;
int i;
for (i = 0; i < index; i++) {
current = current->next;
}
return current->data;
}
int main() {
List *list = createList();
add(list, 1);
add(list, 2);
add(list, 3);
printf("%d\n", get(list, 1));
removeAt(list, 1);
printf("%d\n", get(list, 1));
return 0;
}
```
这个程序实现了单链表的基本操作,包括创建链表、添加元素、删除元素、获取元素等。
阅读全文