1.线性表的长度是线性表中元素个数
2.c语言的“结构”类型:
struct node
{
ElemType data;//data为抽象元素类型
struct node *next;//next为指针类型
};
指向结点的指针类型head,p,q说明
struct node *head,*p,*q;
用typedef定义指针类型
typedef struct node
{
ElemType data;
struct node *next;
}node,*Linklist;
指针变量head,p,q的说明
Linklist head,p,q;
3.结点类型的定义
#define LENG sizeof(struct node)
struct nade
{
int data;//数据为int型
struct node* next;
};
4.生成单链表
每次输入新元素后:
1.生成新结点:p=malloc(结点大小)
p->data=e;p->next=null;
2.将结点添加到表尾:tail->next=p;
3.设置新表尾:tail=p;
应用:
a.生成“先进行先出”单链表
struct node*creat1()
{
struct node*head,*tail,*p;
int e;
head=(struct node*)malloc(LENG);
tail=head;
scanf("%d",&e);
while(e!=0)
{
p=(struct node*)malloc(LENG);
p->data=e;
tail->next=p;
tail=p;
scanf("%d",&e);
}
tail->next=null;
return head;
}
b.生成“后进先出”的单链表
struct node*creat2()
{
struct node*head,*p;
int e;
head=(struct node*)malloc(LENG);//生成头结点;
head->next=NULL;//制成空表
scanf("%d",&e);
while(e!=0)
{
p=(struct node*)malloc(LENG);
p->data=e;
p->next=head->next;
head->next=p;
scanf("%d",&e);
}
return head;
}
5.链表的插入,删除
a.在指定位置插入元素:
int insert(LinkList &L,int i,ElemType e)
{
p=L;
j=1;
while(p&&j<i)
{
p=p->next;
j++;
}
if(i<1||p==NULL) return ERROR;//插入点错误;
f=(LinkList)malloc(LENG);
f->data=e;
f->next=p->next;
p->next=f;
return OK;
}
b.在带表头结点的单链表删除元素值为e的结点:
int Deletel(LinkList head,ElemType e)
{
struct node*p,*q;
q=head,p=q->next;
while(p&&p->data!=e)
{
q=p;
p=p->next;
}
if(p)//有元素为e的结点
{
q->next=p->next;
free(p);
return YES;
}
else
return NO;
}
c.删除指定位置上的结点:
int Deletel(LinkList &L,int i,ElemType &e)
{
struct node*q;
p=L;
j=1;
while(p->next&&j<i)
{
p=p->next;
j++;
}
if(i<1||p->next=NULL)
return ERROR;
q=p->next;
p->next=q->next;
e=q->data;
free(q);
return OK;
}
6.循环链表:
a.求以head为头指针的循环链表的长度:
int length(struct node*head)
{
int length=0;
struct node*p;
p=head->next;
while(p!=head)
{
printf("%d",p->data);
p=p->next;
length++;
}
return length;
}