顺序表
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int E;
typedef struct List* ArryList;
struct List
{
E* arry;
int capcity;
int size;
};
int listinit(ArryList list) {
list->arry = NULL;
list->capcity = 10;
list->arry = (E*)malloc(sizeof(E) * list->capcity);
if (list->arry == NULL)return 0;
list->size = 0;
};
int listinsert(ArryList list, int index, E element) {
if (index<1 || index>list->size + 1)return 0;
if (list->size == list->capcity)
{
int newcapcity = list->capcity + (list->capcity >> 1);
E* newArry = (E*)realloc(list->arry, sizeof(E)* newcapcity);
if (newArry == NULL)return 0;
list->arry = newArry;
list->capcity = newcapcity;
}
for (int i = list->size; i > index - 1; i--)
{
list->arry[i] = list->arry[i - 1];
}
list->arry[index - 1] = element;
list->size++;
return 1;
};
void printflist(ArryList list) {
for (int i = 0; i < list->size; i++)
{
printf("%d ", list->arry[i]);
}
};
int deletelist(ArryList list, int index) {
if (index<1 || index>list->size)return 0;
for (int i = index - 1; i < list->size; i++)
{
list->arry[i] = list->arry[i + 1];
}return 1;
}
int findlist(ArryList list, int element) {
for (int i = 0; i < list->size; i++)
{
if (list->arry[i] == element) return i;
}
return 0;
}
int main() {
struct List list;
listinit(&list);
for (int i = 0; i < 30; i++)
{
listinsert(&list, i+1, i * 10);
}
printflist(&list);
}
链表
#include<stdio.h>
#include<stdlib.h>
typedef int E;
struct ListNode
{
E element;
struct ListNode* next;
};
typedef struct ListNode* Node;
int NodeInit(Node head) {
head->next = NULL;
}
int NodeInsert(Node head, int index, int element) {
if (index < 1)return 0;
while (--index)
{
head = head->next;
if (head == NULL)return 0;
}
Node node = malloc(sizeof(struct ListNode));
if (node == NULL)return 0;
node->element = element;
node->next = head->next;
head->next = node;
return 1;
}
int NodeDelete(Node head, int index) {
if (index < 1)return 0;
while (--index) {
head = head->next;
if (head == NULL)return;
}
Node temp = head->next;
head->next = head->next->next;
free(temp);
}
void printfnode(Node head) {
while (head->next)
{
head = head->next;
printf("%d ", head->element);
}
printf("\n");
}
int GetNodeElement(Node head, int index) {
if (index < 1)return 0;
while (index--)
{
head = head->next;
if (head == NULL)return 0;
}
return head->element;
}
int FindNodeElement(Node head,int element) {
int index = 0;
while (head->next)
{
head = head->next;
index++;
if (head->element == element)return index;
}
}
int NodeSize(Node head) {
head = head->next;
int index = 0;
while (head)
{
head = head->next;
index++;
}
return index;
}
int main()
{
struct ListNode head;
NodeInit(&head);
for (int i= 0; i < 10; i++)
{
NodeInsert(&head, i+1, i *10);
}
NodeDelete(&head, 1);
printfnode(&head);
printf("%d\n", GetNodeElement(&head, 9));
printf("%d\n",FindNodeElement(&head, 70));
printf("%d\n", NodeSize(&head));
}