王道数据结构思维导图7:单链表
按位插入代码(带头结点)
bool ListInsert(LinkList &L,int i ,ElemType e){
//在第i个位置插入e
if(i<1)
return false;
LNode *p;
p=L;
int j=0;
//i从1开始,j是i前面的元素,从0开始
while(p!=null&&j<i-1){
p=p->next;
j++;
}
if(p==null)
return false;
LNode *s=(LNode*)malloc(sizeof(LNode));
s->data=e
s->next=p->next;
p->next=s;
return true;
按位插入代码(不带头结点)
bool ListInsert(LinkList &L,int i,int e){
if(i<1)
return false;
LNode *p;
p=L;
j=1;
LNode *s=(LNode*)malloc(sizeof(LNode));
s->data=e;
if(i==1){
s->next=L;
L=s;
return true;
}else{
while(p!=null&&j<i-1){
p=p->next;
j++;
}
s->next=p->next;
p->next=s;
return true;
}
按位插入时间复杂度为O(n)
指定节点后插操作
bool InsertNextNode(LNode *p,ElemType e){
if(p==null)
return false;
LNode *s=(LNode*)malloc(sizeof(LNode))
if(s==null)
return false;
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
指定节点前插操作
bool InsertPriorNode(LNode *p,LNode *s){
if(p==null||s==null)
return false;
s->nest=p->next;
p->next=s;
ElemType aa=p->data;
p->data=s->data;
s->data=aa;
return true;
}
指定节点后插操作和指定节点前插操作都省查找到该节点的过程
按位序删除(带头结点)
bool ListDelete(LinkList &l,int i,ElemType &e){
if(i<1)
return false;
LNode *p;
int j=0;
while(p!=null&&j<i-1){
p=p->next;
j++;
}
if(p->next==null)
return false;
LNode *q=p->next;
e=q->data;
return e;
p->next=q->next;
free(q);
return true;
}
单链表的建立:尾插法
LinkList Taillnsert(LinkList &L){
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode *s, *r=L;
//r是表尾指针
scanf("%d",&x);
while(x!=99999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
}
r->next=Null;
return L;
}
单链表的建立:头插法
LinkList Headlnsert(LinkList &L){
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode *s;
l->next=null;
scanf("%d",&x);
while(x!=99999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
l->next=s;
scanf("%d",&x);
}
return L;
}