尾插法构建双链表并遍历(C语言)

前言

双链表是指,不光有后缀指针,还有前缀指针,需要注意的是,要与双向循环链表区别,在双链表中,表头结点的前缀指向NULL,表尾结点的后缀指向NULL;

双链表的定义

typedef struct Dnode{
     
    struct Dnode *next;
    struct Dnode *prior;
    int data;
}Dnode,*DnodeLinkedList;

双链表的构造(尾插法)

	//构造双链表
    DnodeLinkedList DL = (DnodeLinkedList)malloc(sizeof(Dnode));
    DL->prior = NULL;
    Dnode *s,*r = DL;
    int input_data;
    scanf("%d",&input_data);
    while(input_data!=-999)
    {
     
        s = (Dnode*)malloc(sizeof(Dnode));
        s->data = input_data;
        r->next = s;
        s->prior= r;
        r = s;
        scanf("%d",&input_data);

    }
    r->next = NULL;

遍历


    // 从前向后遍历
    printf("从前向后遍历 ");
    Dnode *p = DL;
    while(p->next!=NULL)
    {
     
        p = p->next;
        printf("%d ",p->data);
    }

    // 从尾部向前遍历
    printf("尾部向前遍历 ");
    Dnode *q = r;
    printf("%d ",q->data);
    while(q->prior!=DL)
    {
     
        q = q->prior;
        printf("%d ",q->data);
    }

完整程序

#include 
#include 
typedef struct Dnode{
     
    struct Dnode *next;
    struct Dnode *prior;
    int data;
}Dnode,*DnodeLinkedList;


int main()
{
     

    //构造双链表
    DnodeLinkedList DL = (DnodeLinkedList)malloc(sizeof(Dnode));
    DL->prior = NULL;
    Dnode *s,*r = DL;
    int input_data;
    scanf("%d",&input_data);
    while(input_data!=-999)
    {
     
        s = (Dnode*)malloc(sizeof(Dnode));
        s->data = input_data;
        r->next = s;
        s->prior= r;
        r = s;
        scanf("%d",&input_data);

    }
    r->next = NULL;

    // 从前向后遍历
    printf("从前向后遍历 ");
    Dnode *p = DL;
    while(p->next!=NULL)
    {
     
        p = p->next;
        printf("%d ",p->data);
    }

    // 从尾部向前遍历
    printf("尾部向前遍历 ");
    Dnode *q = r;
    printf("%d ",q->data);
    while(q->prior!=DL)
    {
     
        q = q->prior;
        printf("%d ",q->data);
    }

    return 0;
}

运行结果

尾插法构建双链表并遍历(C语言)_第1张图片

你可能感兴趣的:(数据结构,指针,printf,链表,c语言)