顺序存储
#include <stdio.h>
#define ListSize 10000
typedef int DataType;
typedef struct
{
DataType data[ListSize];
int lenght;
}SeqList;
void InitList(SeqList * L){
L->lenght = 0;
}
DataType DeleteList(SeqList *L,int i){
int x;
if(i<1 || i>L->lenght+1){
printf("%s\n","Delete error" );
return 0;
}
x = L->data[i-1];
for (int j = i; j <= L->lenght; j++)
{
L->data[j-1]=L->data[j];
}
L->lenght--;
return x;
}
void InsertList(SeqList * L,int i,DataType x){
if(i<1 || i>L->lenght+1){
printf("%s\n","Insert error 1" );
return;
}
if(L->lenght >= ListSize){
printf("%s\n", "Insert error 2");
return;
}
for (int j = L->lenght-1; j >= i; j--)
{
L->data[j+1]=L->data[j];
}
L->data[i-1]=x;
L->lenght++;
}
int main(int argc,char ** argv){
SeqList seqlist;
InitList(&seqlist);
for (int i = 0; i < 100; ++i)
{
InsertList(&seqlist,i+1,i*2);
}
DeleteList(&seqlist,2);
printf("%d\n",seqlist.lenght);
return 1;
}
链式存储
#include <stdio.h>
#include <stdlib.h>
typedef char DataType;
//链表结构
typedef struct node
{
DataType data;
struct node * next;
}ListNode;
typedef ListNode * LinkList;
//头插法
LinkList CreateListF(){
LinkList head;//头结点指针
ListNode *p;
char ch;
head=NULL;
ch=getchar( );
while(ch!='\n'){
p = (ListNode *) malloc(sizeof(ListNode));
p->data=ch;
p->next=head;
head=p;
ch=getchar() ;
}
return head;
}
//尾插法
LinkList CreateListR(){
LinkList head,rear;//分别指向头、尾指针
ListNode * p;
char ch;
head=NULL;rear=NULL;
ch=getchar( );
while(ch!='\n'){
p = (ListNode *) malloc(sizeof(ListNode));
p->data=ch;
printf("输入字符:%c\n", ch);
if(head==NULL){
head=p;
}else{
rear->next=p;
}
rear=p;
ch=getchar( );
}
if(rear!=NULL){
rear->next=NULL;
}
return head;
}
//带头结点插法
LinkList CreateListH(){
LinkList head = (ListNode *) malloc(sizeof(ListNode));
ListNode *p,*r;
char ch;
r=head;
while((ch=getchar( ))!='\n'){
p = (ListNode *) malloc(sizeof(ListNode));
p->data=ch;
printf("输入字符:%c\n", ch);
r->next=p;
r=p;
}
r->next=NULL;
return head;
}
//i:结点序号
ListNode * GetNode(LinkList head,int i){
ListNode *p; int j;
p=head->next;j=1;
while(p!=NULL && j<i){
p=p->next;++j;
}
if(j==i){
return p;
}else{
return NULL;
}
}
//根据值查找
ListNode * GetNodeV(ListNode * head,DataType value){
LinkList p = head->next;
while(p->next!=NULL && p->data !=value){
p=p->next;
}
return p;
}
//插入
//head:头结点
//i:序列
//x:插入的值
void InsertList(LinkList head,int i,DataType x){
ListNode *p,*s;int j;
p=head;
j=0;
while(p!=NULL && j<i-1){
p=p->next;
j++;
}
if(p==NULL){
printf("%s\n", "error");
}else{
s = (ListNode *) malloc(sizeof(ListNode));
s->data=x;
s->next=p->next;
p->next=s;
}
}
int main(int argc,char ** argv){
LinkList ll = CreateListH();
InsertList(ll,3,'h');
printf("查找结点值为:%c\n",GetNode(ll,3)->data);
printf("查找结点值为:%c\n",GetNodeV(ll,'h')->data);
return 0;
}