链表及其操作

#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <math.h>
using namespace std;
typedef struct LNode{
    int data;
    struct LNode *next,*prior;
}LNode,*LinkList;
//头插法 (顺序与输入顺序相反)
void CreatList1(LinkList &L){
    LNode *s;
    int x;
    L=(LinkList)malloc(sizeof(LNode));        //创建头结点
    L->next=NULL;
    scanf("%d",&x);
    while(x!=0){
        s=(LNode*)malloc(sizeof(LNode));
        //s.data=x;
        s->data=x;
        s->next=L->next;
        L->next=s;
        scanf("%d",&x);
    }

}
//尾插法
void CreatList2(LinkList &L){
    int x;
    L=(LinkList)malloc(sizeof(LNode));
    L->next=NULL;
    LNode *s,*r=L;
    scanf("%d",&x);
    while(x!=0){
         s=(LNode*)malloc(sizeof(LNode));
        s->data=x;
        r->next=s;
        r=s;
        scanf("%d",&x);

    }
     r->next=NULL;
}
//按序号查找结点值

LNode *getElem(LinkList L ,int i){
    LNode *p=L->next;
    int j=1;
    while(j<i){
        p=p->next;
        j++;
    }
    return p;
}

//按值查找表结点

LNode *getELem2(LinkList L,int x){
    LNode *p=L->next;
    while(p->data!=x&&p!=NULL){
        p=p->next;
    }
    return p;
}

//插入结点

void insertNode(LinkList L,int index,LNode *d){
    //在序号index 后面加入节点d
    LNode *s=getElem(L,index);
    cout<<s->data<<"   jia "<<d->data<<endl;
    d->next=s->next;
    s->next=d;


}
//删除结点

void deleteNode(LinkList L,int index){
    //删除第index个结点
    LNode *p=getElem(L,index-1);
    LNode *q=p->next;
    p->next=q->next;
    free(q);
}


/*以下是双链表的操作  ,双链表仅仅是在单链表的基础上加上了前驱结点,
在单链表中,如果要访问某个结点的前驱结点,只能从头扫描
但是双链表 有 2 个指针,prior 和 next ,分别指向前驱结点和后继结点。
*/

//双链表的插入操作

void insertNode2(LinkList L,int index,LNode *s){
    //插在第index结点的后面
    LNode *p=getElem(L,index);
    s->next=p->next;
    p->next->prior=s;
    p->next=s;
    s->prior=p;
}


//双链表的删除操作

void deleteNode2(LinkList L,int index){
    //删除第index 个结点
    LNode *p=getElem(L,index);
    p->prior->next=p->next;
    p->next->prior=p->prior;
    free(p);
}
int main() { LinkList L; CreatList2(L); LNode *p; p=(LNode *)malloc(sizeof(LNode)); p->data=1000; p->next=NULL; insertNode(L,4,p); //打印链表 LNode *s=L; while(s->next!=NULL){ s=s->next; cout<<s->data<<" "; } cout<<endl; //deleteNode(L,4); int x; printf("请输入要删除的值\n"); scanf("%d",&x); cout<<x<<endl; deleteX(x,1,L); LNode *m=L; while(m->next!=NULL){ m=m->next; cout<<m->data<<" "; } cout<<endl; return 0; }

 

posted @ 2016-07-26 08:52  咸咸的告别  阅读(272)  评论(1编辑  收藏  举报