数据结构实验之链表九:双向链表

来源:互联网 发布:java中排序算法 编辑:程序博客网 时间:2024/05/17 22:32


这道题的算法思想就是给结点再加一个前驱指针,使它指向它的前面的结点,注意创建双向链表时要把head结点的前驱指针置空。

代码如下:

#include <stdio.h>
#include <malloc.h>
struct node{/*双向链表的定义*/
    int data;
    struct node* prior,*next;/*加上一个前驱指针*/
};
struct node* Createlist(int n){/*创建双向链表*/
    struct node* head,*tail,*p;
    head=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    head->prior=NULL;/*把头结点的前驱指针置空*/
    tail=head;
    int i,d;
    for(i=1;i<=n;i++){
        scanf("%d",&d);
        p=(struct node*)malloc(sizeof(struct node));
        p->data=d;
        p->next=NULL;
        p->prior=tail;
        tail->next=p;
        tail=p;
    }
    return head;
};
int main(){
    int m,n,i,d;
    scanf("%d %d",&n,&m);
    struct node* head,*p;
    head=Createlist(n);
    for (i=1;i<=m;i++){
        scanf("%d",&d);
        for(p=head->next;p!=NULL;p=p->next){
            if(d==p->data){
                if(p->prior!=NULL&&p->next!=NULL&&p->prior!=head){
                    if (i==m)
                        printf("%d %d",p->prior->data,p->next->data);
                    else
                        printf("%d %d\n",p->prior->data,p->next->data);
                }
                else if(p->next==NULL){
                    if(i==m)
                        printf("%d",p->prior->data);
                    else
                        printf("%d\n",p->prior->data);
                }
                else if(p->prior==head){
                    if(i==m)
                        printf("%d",p->next->data);
                    else
                        printf("%d\n",p->next->data);
                }
            }
        }
    }
    return 0;
}

0 0
原创粉丝点击