双链表创建,插入和删除

发布时间:2024年01月02日
#include <stdio.h>
#include <stdlib.h>


typedef struct Node{
    int data;
    struct Node* previous;
    struct Node* next;
}Node;
void create_doublelink(Node* Head,int length);
void print_link(Node*);
void insert_link(Node*,int);
void delete_link(Node* ,int );

int main()
{
    Node* Head=(Node*)malloc(sizeof(Node));
    Node* ptr=Head;

    create_doublelink(ptr,10);
    insert_link(ptr,7);
    delete_link(ptr,5);
    print_link(ptr);

    return 0;
}

void create_doublelink(Node* Head,int length)
{
    Node* searchtail=Head; 
    for(int i=0;i<length;i++)//定义length个节点
    {
        /*定义一个新的节点,进行新节点初始化*/
        Node* newNode=(Node*)malloc(sizeof(Node));
        newNode->data=10*i+10;
        newNode->previous=NULL;
        newNode->next=NULL;
        /*search指向最后一个节点*/
        while((searchtail->next)!=NULL)
        {        
            searchtail=searchtail->next;
        }
        searchtail->next=newNode;
        newNode->previous=searchtail;    
    }
}

/*从尾结点到头结点打印*/
void print_link(Node* Head)
{
    Node* search=Head->next;
    while((search->next)!=NULL)//找到尾结点
    {
        search=search->next;}
    while(search!=Head)
    {       
        printf("%d\n",search->data); 
        search=search->previous;
    }
}

/*在某个位置插入新节点*/ 
void insert_link(Node* Head,int rank)
{
    Node* search_pre=Head;
    Node* search_next=NULL;  
    /*找到待插入节点前一节点*/  
    for(int i=0;i<rank-1;i++)
    {
        search_pre=search_pre->next;
    }
    search_next=search_pre->next;
    /*创建新节点,进行插入*/
    Node* insertNode=(Node*)malloc(sizeof(Node));
    insertNode->previous=search_pre;
    search_pre->next=insertNode;
    insertNode->next=search_next;
    search_next->previous=insertNode;
    insertNode->data=99;
}

void delete_link(Node* Head,int rank)
{
    Node* search_pre=Head;
    Node* search_current=NULL;  
    /*找到待删除节点前一个节点和需要删除的当前节点*/
    for(int i=0;i<rank-1;i++)
    {
        search_pre=search_pre->next;
    }
    search_current=search_pre->next;
    /*链接当前节点前后节点,删除当前节点*/
    search_pre->next=search_current->next;
    (search_current->next)->previous=search_pre;
    free(search_current);
    search_current=NULL;
}

文章来源:https://blog.csdn.net/weixin_46855342/article/details/135330765
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。