线性表的链式表示和实现

本文介绍了如何在C语言中使用结构体和指针实现线性列表的链式表示,包括创建节点、在开头和结尾插入元素以及显示列表内容的方法。
摘要由CSDN通过智能技术生成

线性列表的链式表示(也称为链接表示)是使用节点实现的,其中每个节点都包含数据元素和指向列表中下一个节点的指针。下面是 C 语言中线性列表的链式表示和实现示例:

 

'''c

 

#include <stdio.h>

#include <stdlib.h>

 

struct Node {

    int data;

    struct Node* next;

};

 

// Function to create a new node

struct Node* createNode(int data) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = data;

    newNode->next = NULL;

    return newNode;

}

 

// Function to insert an element at the beginning of the list

struct Node* insertAtBeginning(struct Node* head, int data) {

    struct Node* newNode = createNode(data);

 

    if (head == NULL) {

        return newNode;

    }

 

    newNode->next = head;

    return newNode;

}

 

// Function to insert an element at the end of the list

struct Node* insertAtEnd(struct Node* head, int data) {

    struct Node* newNode = createNode(data);

 

    if (head == NULL) {

        return newNode;

    }

 

    struct Node* current = head;

    while (current->next != NULL) {

        current = current->next;

    }

 

    current->next = newNode;

    return head;

}

 

// Function to display the elements of the list

void displayList(struct Node* head) {

    struct Node* current = head;

 

    while (current != NULL) {

        printf("%d ", current->data);

        current = current->next;

    }

 

    printf("\n");

}

 

int main() {

    struct Node* head = NULL;

 

    head = insertAtBeginning(head, 3);

    head = insertAtEnd(head, 5);

    head = insertAtEnd(head, 7);

 

    displayList(head);

 

    return 0;

}

 

'''

 

在此实现中,“struct Node”用于表示列表中的每个节点。“createNode”函数负责创建一个新节点并初始化其数据和下一个指针。“insertAtBeginning”函数通过更新新节点的下一个指针以指向当前头,并将新节点作为新头返回,在列表的开头插入一个新节点。“insertAtEnd”函数通过遍历列表直到到达最后一个节点,然后更新最后一个节点的下一个指针以指向新节点,在列表末尾插入一个新节点。'displayList' 函数遍历列表并打印每个节点的数据。

 

在“main”函数中,我们创建一个空列表,然后使用“insertAtBeginning”和“insertAtEnd”函数在列表的开头和结尾插入元素。最后,我们使用“displayList”函数来打印列表的元素。根据对线性列表的链式实现的要求修改和扩展此代码。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BlurryFace36549

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值