双链表创建

#include<stdio.h>
#include<stdlib.h>
typedef struct node {
    int data;
    struct node * prev;
    struct node * next;
}*Lnode,Node;


Lnode appendNode(Lnode head);//添加节点
void deleteNode(Lnode head);//删除节点
void printNode(Lnode head);//打印链表
void freeNode(Lnode head);//释放链表

int main()
{
    char c;
    Lnode head = NULL;
    head = (Lnode)malloc(sizeof(Node));
    head->next = NULL;
    printf("你想创建链表吗?(Y/N)");
    scanf_s("%c", &c);
    while (c == 'y' || c == 'Y')
    {
        getchar();
        head = appendNode(head);
        printf("你想创建链表节点吗?(Y/N)");
        scanf_s("%c", &c);
    }
    printNode(head);
    getchar();
    printf("\n你想删除链表节点吗?(Y/N)");
    scanf_s("%c", &c);
    if (c == 'y' || c == 'Y')
    {
        deleteNode(head);
    }
    printNode(head);
    getchar();
    freeNode(head);

}
Lnode appendNode(Lnode head)
{
    Lnode pr, p;
    pr = head;
    p = (Lnode)malloc(sizeof(Node));
    if (p == NULL)
    {
        printf("申请内存失败!");
        exit(0);
    }
    if (pr->next == NULL)//链表为空,直接把节点插在头节点之后
    {
        pr->next = p;
        p->prev = pr;
        p->next = NULL;
    }
    else //链表不为空,则把节点插在最后一个
    {
        while (pr->next != NULL)
        {
            pr = pr->next;
        }
        pr->next = p;
        p->prev = pr;
        p->next = NULL;
    }
    printf("请输入节点数据:");
    scanf_s("%d",&(p->data));
    getchar();
    return head;
    
}

void deleteNode(Lnode head)
{
    Lnode p = head;
    Lnode pr;
    int c=0;
    int i = 1;
    printf("请输入你想删除的节点位置:");
    scanf_s("%d",&c);
    while (i < c)
    {
        p = p->next;
        i++;
    }
    if (p->next == NULL)
    {
        printf("该位置超过了链表长度!");
        exit(0);
    }
    pr = p->next;
    p->next = p->next->next;
    if (pr->next != NULL)
    {
        pr->next->prev = p;
    }
    free(pr);
    
}

void printNode(Lnode head)//打印链表
{
    Lnode pr;
    pr = head->next;
    while (pr != NULL)
    {
        printf("%5d", pr->data);
        if (pr->next == NULL)
        {
            break;
        }
        else
        {
            pr = pr->next;
        }
    }
}

void freeNode(Lnode head)//释放链表
{
    Lnode p, pr;
    pr = head;
    while (pr != NULL)
    {
        p = pr;
        pr = pr->next;
        free(p);
    }
}

 

上一篇:【数据结构复习】链表的倒置(头插法倒置)


下一篇:代码区——单链表