一 、顺序表
基本定义
typedef struct
{
int data[MAXSIXE];
int len;
}SeqList;
基本操作
//初始化
SeqList *Init_SeqList()
{
SeqList *L;
L=(SeqList*)malloc(sizeof(SeqList));
L->len=0;
return L;
}
//创建线性表
void CreateList(SeqList *L)
{
int i;
printf("Input length of List:");
scanf("%d",&i);
printf("Input element of List: \n");
for(i=1;i<n;i++)
scanf("%d",&L->data[i]);
}
插入操作:注意从第i个元素之前插入,所以从后面往前面插入,第i个元素及其之后的元素整体后移。判断插入位置是否合法 (i < 1 || i > L->len+1)。最后不要忘记改变顺序表的长度。
void Insert(SeqList *L,int i,int x)
{
int j;
if(L->len==MAXSIZE-1)
printf("FULL!\n");
else if(i<1||i>L->len+1)
printf("The position is invalid!\n");
else
{
for(j=L->len;j>=i;j--)
L->data[j+1]=L->data[j];
L->data[i]=x;
L->len++;
}
}
删除操作:注意判断删除位置条件 (i < 1 || i>L -> len)
void delete(SeqList *L,int i)
{
int j;
if(L->len==0)
printf("EMPTY!\n");
else if(i<1||i>L->len)
printf("The position is invalid!\n");
else
{
for(j=i+1;j<=L->len;j++)
L->data[j-1]=L->data[j];
L->len--;
}
}
查找操作:下面的方法是只要查找到第一个与x相同的元素就返回该元素的位置。第二个算法是将待查找的值存入0号位置,从后往前查找。
int Location1(SeqList *L,int x)
{
int i=1;
while(i<L->len&&L->data[i]!=x)
{
i++;
}
if(L->data[i]==x)
return i;
else
return 0;
}
int Location2(SeqList *L,int x)
{
int i;
i=L->len;
L_>data[0]=x;
while(L->data[i]!=x)
i--;
return i;
}
二、单链表
基本定义
typedef struct node
{
char data;
struct node *next;
}LNode;
基本操作
在表头插入生成单链表:将主函数中指向待生成单链表的指针地址如(&p)传给**head,*head为链表头指针。
//head insert
void CreatLinkList(LNode **head)
{
char x;
LNode *p;
*head=(LNode*)malloc(sizeof(LNode));
(*head)->next=NULL;
printf("Input any char string:\n");
scanf("%c",&x);
while(x!='\n')
{
p=(LNode*)malloc(sizeof(LNode));
p->data=x;
p->next=(*head)->next;
(*head)->next=p;
scanf("%c,&x");
}
}
在表尾插入生成单链表:p指针用来记录q指针的前驱。
//tail insert
void CreatLinkList(LNode **head)
{
LNode *head,*p,*q;
char x;
head=(LNode*)malloc(sizeof(LNode));
p->data=x;
p->next=NULL;
q=p; //指针q指向新的链尾节点*p
scanf("%c",&x);
{
while(x!='\n')
{
p=(LNode*)malloc(sizeof(LNode));
p->data=x;
p->next=NULL;
q->next=p;
scanf("%c",&x);
}
}
}
删除第i个结点:注意查找第i-1个节点。
//查找第i个节点
LNode *Get_LinkList(LNode *head,int i)
{
LNode *p=head;
int j=0;
while(p!=NULL&&j<i)
{
p=p->next;
j++;
}
return p;
}
void Delete(LNode *head,itn i)
{
LNode *p,*q;
p=Get_LinkList(head,i-1);
if(p==NULL)
printf("第i-1个节点不存在!!\n");
else if(p->next==NULL)
printf("第i个节点不存在!\n");
else
{
q=p->next; //q指向第i个节点
p->next=q->next; //从链表删除第i个节点
free(q);// 系统回收第i个节点的存储空间
}
}
三、双向链表
基本定义
typedef struct dlnode
{
char data;
struct dlnode *prior,*next;
}DLNode;
基本操作
采用头插法生成双向链表:
DLNode *CreatDLinkList()
{
DLNode *head,*s;
char x;
head=(DLNode*)malloc(sizeof(DLNode));
head->prior=head;
head->next=head;
printf("Input any char string\n");
scanf("%c",&x);
//采用头插法生成双向循环链表
while(x!='\n');
{
s=(DLNode*)malloc(sizeof(DLNode));
s->data=x;
s->prior=head;
s->next=head->next;
head->next->prior=s;
scanf("%c",&x);
}
return head;
}
如下是双向链表的插入操作:注意顺序不能搞错