main
#include <stdio.h>
#include <stdlib.h>
#include "list2.h"
int main()
{
list *l;
int u = 0;
datatype arr[] = {3,4,5,67,8,3,3};
l = list_creat();
if(l == NULL)
return 1;
for(int i = 0; i< sizeof(arr) / sizeof(*arr); i++)
{
// u = list_insert_at(l,0,&arr[i]);
u = list_order_inser(l,&arr[i]);
if(u != 0)
{
printf("%d\n",u);
return 1;
}
}
list_display(l);
datatype value = 3;
//list_delete(l,&value);
list_delete_at(l,3,&value);
printf("f = %d\n",value);
list_display(l);
return 0;
}
list.h
#ifndef __LIST22__
#define __LIST22__
#include <stdio.h>
#include <stdlib.h>
#include "list2.h"
typedef int datatype;
typedef struct node_st
{
datatype data;
struct node_st *next;
}list;
list *list_creat();
int list_insert_at(list *me,int i,datatype * data);
int list_order_inser(list *me,datatype *data);
int list_delete_at(list *me,int i,datatype *data);
int list_delete(list *me,datatype *data);
void list_display(list *me);
int list_isempty(list *me);
void list_destory(list *me);
#endif
list.c
#include <stdio.h>
#include <stdlib.h>
#include "list2.h"
list *list_creat()
{
list *me;
me = malloc(sizeof(*me));
if(me == NULL)
return NULL;
me->next = NULL;
return me;
}
//插入一个到指定位置
int list_insert_at(list *me,int i,datatype * data)
{
int j = 0;
list *node = me;
list *newnode = NULL;
if(i < 0) return -1;
while(j < i && node != NULL) //找到第i个节点
{
node = node->next;
j++;
}
if(node != NULL)
{
newnode = malloc(sizeof(*newnode));
if(newnode == NULL)
return -2;
newnode->next = node->next;
node->next = newnode;
newnode->data = *data;
return 0;
}
else
{
return -3;
}
}
void list_display(list *me)
{
list *node = me->next;
if(list_isempty(me) == 0)
return;
while(node != NULL)
{
printf(" %d ",node->data);
node = node->next;
}
printf("\n");
return;
}
int list_order_inser(list *me,datatype *data)
{
list *p = me,*q;
while(p->next != NULL && p->next->data < *data)
{
p = p->next;
}
q = malloc(sizeof(*q));
if(q == NULL)
return -1;
q->data = *data;
q->next = p->next;
p->next = q;
return 0;
}
int list_delete_at(list *me,int i,datatype *data)
{
int j = 0;
list *p = me,*q;
*data = -1; //这里给空
while(j < i)
{
j++;
p = p->next;
}
if(p)
{
q = p->next;
p->next = q->next;
*data = q->data;//回填删除的元素
free(q);
q = NULL;
return 0;
}
else return -2;
}
int list_delete(list *me,datatype *data)
{
list *p = me;
list *q = NULL;
while(p->next && p->next->data != *data)
p = p->next;
if(p->next == NULL)
{
return -1;
}
else
{
q = p->next;
p->next = q->next;
free(q);
q = NULL;
}
return 0;
}
int list_isempty(list *me)
{
if(me->next == NULL)
return 0;
return 1;
}
void list_destory(list *me)
{
list *node;
list *next;
for(node = me->next;node != NULL;node = next)
{
next = node->next;
free(node);
}
free(me);
}