自己实现双向链表

实现双向链表:创建、插入、删除

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

typedef struct student
{
    int data;
    struct student *next;
    struct student *pre;
}dnode;

//创建链表
dnode *create()
{
    dnode *head;
    dnode *p;
    dnode *s;
    int x = 0;
    int cycle = 1;

    head = (dnode*)malloc(sizeof(dnode));
    p = head;

    while(cycle)
    {
        printf("input the data:");
        scanf("%d", &x);

        if (x != 0)
        {
            s = (dnode*)malloc(sizeof(dnode));
            s->data = x;
            p->next = s;
            s->pre = p;
            p = s;
        }
        else
        {
            cycle = 0;
        }
    }

    p->next = NULL;
    p = head;
    head = head->next;
    free(p);
    p = NULL;

    return head;
}

//插入节点
dnode *insert(dnode *head, int num)
{
    dnode *p0;
    dnode *p1;
    p1 = head;
    p0 = (dnode*)malloc(sizeof(dnode));
    p0->data = num;

    while(p0->data > p1->data && p1->next != NULL)
    {
        p1 = p1->next;
    }

    if (p0->data <= p1->data)
    {
        if (head == p1)
        {
            p0->next = p1;
            p1->pre = p0;
            head = p0;
        }
        else
        {
            p1->pre->next = p0;
            p0->next = p1;
            p0->pre = p1->pre;
            p1->pre = p0;
        }
    }
    else
    {
        p1->next = p0;
        p0->pre = p1;
        p0->next = NULL;
    }

    return head;
}

//删除节点
dnode *del(dnode *head, int num)
{
    dnode *p1;
    p1 = head;

    while (num != p1->data && p1->next != NULL)
    {
        p1 = p1->next;
    }

    if (num == p1->data)
    {
        if (p1 == head)
        {
            head = head->next;
            head->pre = NULL;
            free(p1);
        }
        else if (p1->next == NULL)
        {
            p1->pre->next = NULL;
            free(p1);
        }
        else
        {
            p1->next->pre = p1->pre;
            p1->pre->next = p1->next;
            free (p1);
        }
    }
  else
    {
        printf("not found:%d\n", num);
    }

    return head;
}

//计算链表长度
int length(dnode *head)
{
    dnode *p;
    int n = 0;
    p = head;

    while(p != NULL)
    {
        p = p->next;
        n++;
    }

    printf("len:%d\n", n);
    return n;
}

//显示
void show(dnode *head)
{
    dnode *p;
    int n = 0;
    p = head;

    while(p != NULL)
    {
        printf("data:%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

int main()
{
    dnode *head = create();
    show(head);
    length(head);

    head = insert(head, 2);
    show(head);

    head = del(head, 2);
    show(head);


}

猜你喜欢

转载自www.cnblogs.com/etangyushan/p/10704112.html
今日推荐