数组,存储空间大,且连续,而链表与之相反,它的存储区域是不连续的空间单元;
链表中除了头节点没有前驱,尾节点没有后继之外,其余都会有前驱和后继(此文中暂不提及环链)
链表的每个节点都是一个结构体单元,至少有两个域,一个为值域,一个为存储下一个节点地址的指针域
其结构体可声明为:
typedef struct node{
int data;
struct node *next;
}ElemSN;
创建一条链:
ElemSN *createlink(int n)
{
ElemSN *h;
int x;
if(n){
h=(ElemSN *)malloc(sizeof(ElemSN));
scanf("%d",&x);
h->data=x;
h->next=createlink(--n);
}
return h;
}
ElemSN *createlink2(int n)
{
ElemSN *h,*p,*t;
int x;
int i;
for(i=0;i<n;i++){
p=(ElemSN *)malloc(sizeof(ElemSN));
scanf("%d",&x);
p->next=NULL;
p->data=x;
if(!i) h=t=p;
else t=t->next=p;
}
return h;
}
单向遍历链表:
void PrintLink(ElemSN *h){
ElemSN *p;
for(p=h;p;p=p->next){
printf("%d",p->data);
}
}
反向输出链表:
void NPrintLink(ElemSN *h){
ElemSN *p,*end;
end=NULL;
while(end-h){
for(p=h;p->next-end;p=p->next);
printf("%d",p->data);
end=p;
}
}
删除节点(假设有重复的点–我遇到一面试题):
ElemSN * Delete(ElemSN *h,int key){
ElemSN *p,*q,*t,*head;
head=h;
for(p=h;p;p=p->next){
if(p->data==key){ //若为头节点
q=t=p;
if(p==h) head->next=h->next;
else{
q->next=p->next;
}
free(t);
}
}
if(!p) printf("Not found\n");
return head;
}
插入一个节点(分为头插,尾插,中间插):
//假设该原链表是有序的
ElemSN * Insert(ElemSN *h,int key){
ElemSN *p,*q,*t,*head;
head=h;
for(p=h;p&&p->data>key;q=p,p=p->next);
t=(ElemSN *)malloc(sizeof(ElemSN));
t->data=key;
t->next=NULL;
if(p==h){ //头插
t->next=h;
head=t;
}else if(p==NULL){//尾插
p->next=t;
}else{//中间插入
t->next=p;
q->next=t;
}
return head;
}