Implementación de listas vinculadas
- Definir la estructura del nodo de la lista vinculada
typedef struct node {
int val;
struct node* next;
} MyLinkedList, node;
- Cree una lista vinculada, es decir, cree un nodo principal
MyLinkedList* myLinkedListCreate() {
MyLinkedList * obj = (MyLinkedList*)malloc(sizeof(node));
obj->next = NULL;
return obj;
}
- Agregue un nodo antes del nodo principal de la lista vinculada como un nuevo nodo principal
void myLinkedListAddAtHead(MyLinkedList* obj, int val) {
node * newNode = (node*)malloc(sizeof(node));
newNode->val = val;
newNode->next = obj->next;
obj->next = newNode;
}
- Agregue un nodo después del nodo final de la lista vinculada como el nuevo nodo final
void myLinkedListAddAtTail(MyLinkedList* obj, int val) {
node * newNode = (node*)malloc(sizeof(node));
newNode->val = val;
newNode->next = NULL;
node* p = obj;
while(p->next != NULL)
p = p->next;
p->next = newNode;
}
- Inserta un nodo en la posición especificada, el valor es val
int myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val) {
node* p = obj;
int j = 0;
while (p && j < index) {
p = p->next;
++j;
}
if (!p || j > index){
printf("ERROR!\n");
return -1;
}
node* newNode = (node*)malloc(sizeof(node));
newNode->val = val;
newNode->next = p->next;
p->next = newNode;
return 0;
}
- Eliminar el nodo en la ubicación especificada
int myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) {
node* p = obj;
int j = 0, val = 0;
while (p->next && j < index) {
p = p->next;
++j;
}
if (!(p->next) || j > index){
printf("ERROR!\n");
return -1;
}
node* q = p->next;
p->next = q->next;
val = q->val;
free(q);
return val;
}
- Obtenga el valor del nodo cuyo número de índice es índice y devuelva -1 si el número de índice es incorrecto
int myLinkedListGet(MyLinkedList* obj, int index) {
node* p = obj->next;
int j = 0;
while (p && j<index) {
p = p->next;
++j;
}
if (!p || j>index){
printf("ERROR!\n");
return -1;
}
return p->val;
}
- Lista de lanzamientos
void myLinkedListFree(MyLinkedList* obj) {
MyLinkedList * Transit;
while(obj->next != NULL) {
Transit = obj;
obj = obj->next;
free(Transit);
}
free(obj);
}
- Imprimir lista vinculada
void showAll(MyLinkedList* obj) {
if(obj->next == NULL) return;
MyLinkedList *mov = obj->next;
while(mov != NULL) {
printf("%d ", mov->val);
mov = mov->next;
}
printf("\n");
}
- Función principal
#include <stdio.h>
#include <malloc.h>
int main() {
MyLinkedList* obj = myLinkedListCreate();
printf("初始的四个结点:");
int i;
for(i = 2; i < 6; i++) {
myLinkedListAddAtTail(obj, i * i);
}
showAll(obj);
printf("首元结点前插入:");
myLinkedListAddAtHead(obj, 1);
showAll(obj);
printf("尾元结点后插入:");
myLinkedListAddAtTail(obj, 36);
showAll(obj);
printf("在指定坐标插入:");
myLinkedListAddAtIndex(obj, 2, 6);
showAll(obj);
printf("在指定坐标删除:");
myLinkedListDeleteAtIndex(obj, 3);
showAll(obj);
printf("获取指定坐标数值:%d\n", myLinkedListGet(obj, 3));
myLinkedListFree(obj);
}
resultado de la operación