继续完善ing.......
链式:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int elem;
struct node *next;
}DataNode;
typedef struct {
int count;
DataNode *next;
}*LinkHead,LinkNode;
int Init(LinkHead *L)
{
LinkHead p=(LinkHead)malloc(sizeof(LinkNode));
DataNode *q=(DataNode *)malloc(sizeof(DataNode));
q->next = NULL;
p->count = 0;
p->next = q;
(*L) = p;
return 0;
}
int Insert(LinkHead *L,int elem,int pos)
{
if(pos<1||pos>(*L)->count+1)
{
return -1;
}
DataNode *q = (DataNode *)malloc(sizeof(DataNode));
q->elem = elem;
DataNode *p=(*L)->next;
for(int i=1;i<pos;i++)
{
p=p->next ;
}
q->next = p->next ;
p->next = q;
(*L)->count += 1;
return 0;
}
int Delete(LinkHead *L,int *elem,int pos)
{
if(pos<1||pos>(*L)->count)
{
return -1;
}
DataNode *p = (*L)->next,*q;
for(int i=1;i<=pos;i++)
{
p=p->next;
}
q=p->next ;
p->next = q->next ;
free(q);
(*L)->count -= 1;
return 0;
}
int Clear(LinkHead *L)
{
DataNode *p=(*L)->next->next,*q;
while(p!=NULL)
{
q = p;
p=p->next ;
free(q);
}
(*L)->next->next = NULL;
(*L)->count = 0;
return 0;
}
int Destory(LinkHead *L)
{
DataNode *p=(*L)->next,*q;
free(*L);
while(p!=NULL)
{
q=p;
p=p->next ;
free(q);
}
(*L)=NULL;
return 0;
}
int Traverse(LinkHead L)
{
DataNode *p=L->next->next ;
for(int i=0;i<L->count ;i++)
{
printf("%d ",p->elem );
p=p->next ;
}
return 0;
}
int main()
{
LinkHead L;
Init(&L);
int n,m;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&m);
Insert(&L,m,1);
}
Traverse(L);
Delete(&L,&m,2);
printf("\n%d\n",m);
Traverse(L);
Clear(&L);
Traverse(L);
return 0;
}
顺序:
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100
#define SIZE 20
typedef struct{
int *elem;
int size;
int count;
}SqList;
int Init(SqList *L)
{
L->elem =(int *)malloc(MAX_SIZE*sizeof(int));
L->count = 0;
L->size = 100;
return 0;
}
int Insert(SqList *L,int pos,int elem)
{
if(pos<1 || pos > L->count+1)
{
return 0;
}
if(L->count == L->size)
{
int *p = (int *)realloc(L->elem ,(L->size+SIZE)*sizeof(int));
if(p == NULL)
{
return -1;
}
L->elem = p;
L->size += SIZE;
}
for(int i=L->count-1;i>=pos-1;i--)
{
L->elem[i+1]=L->elem[i];
}
L->elem[pos-1]=elem;
L->count +=1;
return 0;
}
int Delete(SqList *L,int pos,int *elem)
{
if(pos<1 || pos>L->count)
{
return 0;
}
*elem = L->elem[pos-1];
for(int i=L->count-1;i>=pos-1;i--)
{
L->elem[i-1]=L->elem[i];
}
L->count -= 1;
return 0;
}
int Locate(SqList L,int elem)
{
int i;
for(i=0;i<=L.count-1;i++)
{
if(L.elem[i]==elem)
{
return i+1;
}
}
return 0;
}
int Traverse(SqList L)
{
for(int i=0;i<L.count ;i++)
{
printf("%d\t",L.elem[i]);
}
printf("\n");
return 0;
}
int main()
{
}