C语言数据结构实现-双向链表

前面学习了如何创建一个双向链表,本节学习有关双向链表的一些基本操作,即如何在双向链表中添加、删除、查找或更改数据元素。

本节知识基于已熟练掌握双向链表创建过程的基础上,我们继续上节所创建的双向链表来学习本节内容,创建好的双向链表如图 1 所示:
image

双向链表添加节点

根据数据添加到双向链表中的位置不同,可细分为以下 3 种情况:
添加至表头
将新数据元素添加到表头,只需要将该元素与表头元素建立双层逻辑关系即可。

换句话说,假设新元素节点为 temp,表头节点为 head,则需要做以下 2 步操作即可:
temp->next=head; head->prior=temp;
将 head 移至 temp,重新指向新的表头;

例如,将新元素 7 添加至双链表的表头,则实现过程如图 2 所示:image
添加至表的中间位置
同单链表添加数据类似,双向链表中间位置添加数据需要经过以下 2 个步骤,如图 3 所示:
1、新节点先与其直接后继节点建立双层逻辑关系;
2、新节点的直接前驱节点与之建立双层逻辑关系;
image
添加至表尾
与添加到表头是一个道理,实现过程如下(如图 4 所示):
找到双链表中最后一个节点;
让新节点与最后一个节点进行双层逻辑关系;

双向链表删除节点

双链表删除结点时,只需遍历链表找到要删除的结点,然后将该节点从表中摘除即可。

例如,从图 1 基础上删除元素 2 的操作过程如图 5 所示:

image

双向链表查找节点

通常,双向链表同单链表一样,都仅有一个头指针。因此,双链表查找指定元素的实现同单链表类似,都是从表头依次遍历表中元素。

双向链表更改节点

更改双链表中指定结点数据域的操作是在查找的基础上完成的。实现过程是:通过遍历找到存储有该数据元素的结点,直接更改其数据域即可。

全部代码为

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

typedef struct line{
    struct  line * prior;
    int data;
    struct line * next;
} line;
line * initLine();
void displayLine(line *);
void insertNode(line *,int , int );
void deleteNode(line *,int );
void updateNode(line * , int , int);
int main(){
    line * head = initLine();
    insertNode(head,3, 100);
    insertNode(head,5, 90);
    deleteNode(head,2);
    insertNode(head,3, 77);
    displayLine(head);
}
//修改内容
void updateNode(line * head, int pos , int num){
    line * temp = head;
    for(int i=1;i<pos;i++){
        temp = temp->next;
    }
    temp->data  = num;
}


//删除节点
void deleteNode(line * head, int pos){
    line * temp = head;
    for( int i=1;i<pos-1;i++){
        temp = temp->next;
    }
    temp->next = temp->next->next;
    temp->next->next->prior = temp;
}

//添加节点
void  insertNode(line * Head, int add, int num){
    line * temp = Head;

    line * newNode = (line *)malloc(sizeof(line));
    newNode->data = num;
    newNode->next=NULL;
    newNode->prior=NULL;
    for(int i=1;i<add-1;i++){
        temp = temp->next;
    }
    newNode->next = temp->next;
    temp->next->prior = newNode;

    temp->next = newNode;
    newNode->prior = temp;

}
//初始化
line * initLine(){
    line * head = (line *) malloc(sizeof(line));
    head->data=1;
    head->prior=NULL;
    head->next=NULL;
    line * list = head;
    for(int i=2;i<=4;i++){
        line * node = (line *)malloc(sizeof(line));
        node->prior=NULL;
        node->data = i;
        node->next=NULL;

        list->next = node;
        node->prior=list;

        list = list->next;
    }
    return head;
}
//打印内容
void displayLine(line * head){
    line * temp = head;

    while(temp) {
        printf("%d\n",temp->data);
        temp = temp->next;
    }
}



posted on 2024-06-15 22:35  孤灯引路人  阅读(5)  评论(0编辑  收藏  举报

导航