Linked list implementation
- Define linked list node structure
typedef struct node {
int val;
struct node* next;
} MyLinkedList, node;
- Create a linked list, that is, create a head node
MyLinkedList* myLinkedListCreate() {
MyLinkedList * obj = (MyLinkedList*)malloc(sizeof(node));
obj->next = NULL;
return obj;
}
- Add a node before the head node of the linked list as a new head node
void myLinkedListAddAtHead(MyLinkedList* obj, int val) {
node * newNode = (node*)malloc(sizeof(node));
newNode->val = val;
newNode->next = obj->next;
obj->next = newNode;
}
- Add a node after the end node of the linked list as the new end node
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;
}
- Insert a node at the specified position, the value is 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;
}
- Delete the node at the specified location
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;
}
- Get the value of the node whose index number is index, and return -1 if the index number is wrong
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;
}
- Release list
void myLinkedListFree(MyLinkedList* obj) {
MyLinkedList * Transit;
while(obj->next != NULL) {
Transit = obj;
obj = obj->next;
free(Transit);
}
free(obj);
}
- Print linked list
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");
}
- Main function
#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);
}
operation result