双向链表的查找及插入

在表中第i个元素之前插入一个元素。主要有三个方面:

  • 头结点及尾结点指针域的变化
  • 查找过程中循环条件的变化
  • 插入元素过程中的指针运算

在表建好以后,调用GetElemP_DuL()函数查找第i个元素,返回第i个元素的地址,否则返回空指针。

如图:

程序:

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef struct DuLNode{
        int data;
        struct DuLNode *prior;
        struct DuLNode *next;
}DuLNode,*DuLinkList;
//建立一个只含头结点的空双向循环链表
int InitList_DuL(DuLinkList &L){
        L=(DuLinkList)malloc(sizeof(DuLNode));
        if(!L){
                exit(OVERFLOW);
        }
        L->prior=L;
        L->next=L;
        return OK;
}
int CreateList_DuL(DuLinkList &L,int n){
        DuLinkList p,q;
        int i;
        printf("Input the datas:");
        q=L;
        for(i=0;i<n;i++){
                p=(DuLinkList)malloc(sizeof(DuLNode));
                scanf("%d",&p->data);
                p->next=q->next;
//              p->next=L->next;
                q->next=p;
                p->prior=q;
                L->prior=p;
                q=p;
        }
                return OK;

}
DuLNode *GetElemP_DuL(DuLinkList L,int i){
        DuLinkList p;
        int j=1;
        p=L->next;
     while(p!=L&&j<i){
                p=p->next;//查找第i个节点
                ++j;
        }
        while(p==L||j>i){
                return ERROR;
        }
        return p;
}

int ListInsert_DuL(DuLinkList &L,int i,int &e){
        DuLinkList p,s;
        if(!(p=GetElemP_DuL(L,i))){
                return ERROR;
        }
        if(!(s=(DuLinkList)malloc(sizeof(DuLNode)))){
                return ERROR;
        }//申请新结点
        s->data=e;//s指向新元素e
        s->prior=p->prior;//开始插入,首先是×s的前驱指针
        p->prior->next=s;
        s->next=p;//×s的后继指针
        p->prior=s;
        return OK;
}
int TraverseList_DuL(DuLinkList L){
        DuLinkList p;
        p=L->next;
        while(p!=L){
                printf("%d",p->data);
                p=p->next;
        }
        return OK;
}
main(){
        int i,n,e;
        DuLinkList L;
        InitList_DuL(L);
        printf("Input the length of the list L:");
        scanf("%d",&n);
        CreateList_DuL(L,n);
        printf("Input the insert location:");
        scanf("%d",&i);
        printf("Input the insert data:");
        scanf("%d",&e);
        if(ListInsert_DuL(L,i,e)){
                printf("Output the datas:");
                TraverseList_DuL(L);
        }else{
                printf("Can't insert the data!");
        }
        printf(" ");
}
结果:
android@android-Latitude-E4300:~/work/c/doublelianbiao$ ./listinsertnew
Input the length of the list L:4
Input the datas:1 3 5 7
Input the insert location:2
Input the insert data:9
Output the datas:19357
注意:Linux下的段错误:Segmentation fault (core dumped)和Windows下的运行时错误道理是一样,一般都是内存访问越界了导致。肯定是代码的某处逻辑有问题,访问了野指针啊之类的。

原文地址:https://www.cnblogs.com/shamoguzhou/p/6920603.html