链表顺序表删除插入算法应用总结

//顺序表中,删除所有元素值为k的元素 O(n) O(1)
void Delete(Sqlist &L,int k){
    int num=0;
    int i=0,j=0;
    while(j<=L->length-1){
        if(L->data[j]!=k){
            L->data[i++]=L->data[j++];
        }else{
            j++;
            num++;
        }
    }
    L->length-=num;
}
//在双链表中的值为x的结点之后插入值为y的结点
int insert(LinkList &head,int x,int y){
    LNode *p=head->next;
    LNode *q=(LNode*)malloc(sizeof(LNode));
    q->data=y;
    while(p!=null && p->data!=x){
        p=p->next;
    }
    if(p==null) return 0;
    else{
        if(p->next!=null){//不是尾节点
            p->next->prior=q;
            q->next=p->next;
            p->next=q;
            q->prior=p;
        }else{
            q->next=null;
            p->next=q;
            q->prior=p;
        }
    }
    return 1;
}
//双链表 在x结点之前插入值为y的结点
int insert(LinkList &head,int x,int y){
    LNode *p=head->next;
    LNode *q=(LNode*)malloc(sizeof(LNode));
    q->data=y;
    while(p!=null && p->data!=x){
        p=p->next;
    }
    if(p==null) return 0;
    else{
        p->prior->next=q;
        q->prior=p->prior;
        p->prior=q;
        q->next=p;
    }
    return 1;
}
//双链表L,查找第一个值为x的结点,将其余后继交换
int swap(LinkList &L,int x){
    LNode *p=L->next,*q;
    while(p!=null && p->data!=x){
        p=p->next;
    }
    if(p==null) return 0;
    else{
        q=p->next;
        if(q!=null){
            p->prior->next=q;
            q->prior=p->prior;
            p->next=q->next;
            if(q->next!=null){
                q->next->prior=p;
            }
            q->next=p;
            p->prior=q;
        }
    }
}
//非有序的单链表中 设计一个算法 删除值域重复的点 分析时间复杂度 O(n^2)
void Delete(LinkList &L){
    LNode *p=L->next;
    LNode *q,*r,*t;
    while(p!=null){
        q=p;//
        r=q->next;//
        while(r!=null){
            if(r->data==p->data){//r指向被删除结点
                t=r->next;
                q->next=t;
                free(r);
                r=t;
            }else{
                q=r;
                r=r->next;
            }
        }
        p=p->next;
    }
}
//约瑟夫环
void Josephus(LinkList &L,int m){
    LNode *p=L,*q=&L;
    while(p && p->next){
        for(int i=1;i<m;q=p,p=p->next){
            i++;
        }
        visit(p->data);
        q->next=p->next;
        free(p);
        p=q->next;
    }
    if(p){
        visit(p->data);
        free(p);
    }
    L=null;
}
//顺序表 将所有负数移动到所有正数之前 O(n)
void MoveNumber(int a[],int n){
    int k,i=-1,j=n;
    if(n>0){
        while(i<j){
            do i++;while(a[i]<0 && i>n);
            do j--;while(a[j]>=0 && j>=0);
            if(i<j){
                swap(a[i],a[j]);
            }
        }
    }
}
posted @ 2019-12-26 10:28  ZzUuOo666  阅读(302)  评论(0编辑  收藏  举报