c语言:双向链表(head->data中存储长度)

c语言:双向链表(head->data中存储长度)

1、链表的初始化、插入、删除、遍历、链表长度。 

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

typedef struct node
{
    int data;
    struct node * previous;
    struct node * next;
} Node;

Node * head=(Node*)malloc(sizeof(Node));
Node * tail=(Node*)malloc(sizeof(Node));

void init()
{
    Node *current = head;
    head->next = tail;
    tail->previous = head;
    head->data=0;
    for(int i=1;i<=12;i++)
    {
        Node *new_node=(Node*)malloc(sizeof(Node));
        new_node->data = i;
        new_node->previous = current;
        current->next = new_node;
        new_node->next = tail;
        tail->previous = new_node;
        current = current->next;
        head->data = ++(head->data);//head->data存下链表元素个数!
    }
};
void insert1(int a)
{
    Node * temp1=(Node*)malloc(sizeof(Node));
    temp1->data = a;
    Node * sec=tail->previous;
    sec->next= temp1;
    temp1->previous = sec;
    temp1->next = tail;
    tail->previous = temp1;
    head->data = ++(head->data);//head->data存下链表元素个数!
};
void display()
{
    //printf("%d | ",head->data);
    for(Node* T=head->next;T != tail;T=T->next)
    {
        printf("%d ",T->data);
    }
    printf("  链表长度:%d\n",head->data);
};
Node *find1(int a)
{
    for(Node* T=head->next;T != tail;T=T->next)
    {
        if(T->data == a)
        {
            return T;
        }
    }
    printf("元素中没有%d  ",a);
    return NULL;
};
void delete1(Node *a)
{
    for(Node* T=head->next;T != tail;T=T->next)
    {
        if(T == a)
        {
            Node *T1=T->previous;
            Node *T2=T->next;
            T1->next = T2;
            T2->previous = T1;
            free(T);
            head->data = --(head->data);//head->data存下链表元素个数!
            return;
        }
    }
    printf("元素删除失败\n");
    return;
};
int main()
{
    init();
    display();
    insert1(22);
    display();
    printf("%d\n",find1(100)?find1(100)->data:100);
    delete1(find1(6));
    display();
    return 0;
}
/*
1 2 3 4 5 6 7 8 9 10 11 12   链表长度:12
1 2 3 4 5 6 7 8 9 10 11 12 22   链表长度:13
元素中没有100  100
1 2 3 4 5 7 8 9 10 11 12 22   链表长度:12
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值