数据结构线性表c语言实现

本文介绍了如何使用C语言实现线性链表,重点讨论了C语言中初始化空链表的注意事项,以及指针操作中`.`与`->`的区别。通过代码示例和解析,帮助读者理解相关概念。
摘要由CSDN通过智能技术生成

线性链表的c语言实现代码具体如下

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
//函数结果状态码
#define OK 1
#define ERROR 0
#define false 0
#define true 1
#define INFEASIBLE -3

struct LNode
{
    int data;
    struct LNode *next;
} * LinkList;
//初始化链表
LNode *InitList(int n)
{

    LNode *p, *head;
    LinkList = head = (LNode *)malloc(sizeof(LNode));
    for (int i = 0; i < n; i++)
    {
        p = (LNode *)malloc(sizeof(LNode));
        printf("please input %dth number:", i + 1);
        scanf("%d", &p->data);
        LinkList->next = p;
        LinkList = p;
    }
    LinkList->next = NULL;
    return head;
}
//销毁一个已经存在的链表
int DestroyList(LNode *L)
{
    LNode *q;
    while (q)
    {
        q = L->next;
        free(L);
        L = q;
    }
    return 100;
}
//置空一个链表
void ClearList(LNode *L)
{
    LNode *p, *q;
    p = L->next;
    while (p)
    {
        q = p
  • 7
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是 C 语言实现线性的代码示例: ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 // 定义线性的最大长度 typedef struct { int data[MAX_SIZE]; // 存储数据的数组 int length; // 当前线性的长度 } List; // 初始化线性 void initList(List *list) { list->length = 0; // 线性长度为0 } // 获取线性长度 int getListLength(List *list) { return list->length; } // 在线性末尾插入元素 int insertList(List *list, int element) { if (list->length >= MAX_SIZE) { // 线性已满 return 0; } list->data[list->length++] = element; return 1; } // 删除元素 int deleteList(List *list, int element) { int i, j; for (i = 0; i < list->length; i++) { if (list->data[i] == element) { // 找到要删除的元素 for (j = i; j < list->length - 1; j++) { list->data[j] = list->data[j + 1]; // 将后面的元素向前移动 } list->length--; // 线性长度减1 return 1; } } return 0; // 没有找到要删除的元素 } // 获取某个位置上的元素 int getElement(List *list, int index) { if (index < 0 || index >= list->length) { return -1; // 越界,返回-1 } return list->data[index]; } // 查找元素 int searchList(List *list, int element) { int i; for (i = 0; i < list->length; i++) { if (list->data[i] == element) { return i; // 找到元素,返回下标 } } return -1; // 没有找到元素,返回-1 } int main() { List list; initList(&list); // 初始化线性 // 在线性末尾插入元素 insertList(&list, 1); insertList(&list, 2); insertList(&list, 3); insertList(&list, 4); insertList(&list, 5); // 删除元素 deleteList(&list, 3); // 获取某个位置上的元素 printf("Element at index 2: %d\n", getElement(&list, 2)); // 查找元素 printf("Index of element 4: %d\n", searchList(&list, 4)); return 0; } ``` 以上代码实现线性的基本操作,包括初始化、获取长度、插入元素、删除元素、获取元素、查找元素。注意:本代码仅为示例代码,实际使用中还需根据具体需求进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值