线性表的链式表示和实现

线性表的链式表示和实现

前言:

书中自有颜如玉,书中自有黄金屋。

参考文献:

参考《数据结构》(C语言版) 线性表的链式表示和实现P27~P31

参考博客:https://blog.csdn.net/qq_41523096/article/details/86575377

代码(详细注释)

#include <stdlib.h>
#include <iostream>
using namespace std;
#define ERROR false;
#define OK true;
typedef bool Status;
typedef int ElemType;

struct LNode //链表节点结构体
{
    ElemType data;
    LNode *next;
};

LNode *CreateList_Head(int n) //创建链表头插法
{
    ElemType data;
    LNode *head, *p;
    head = (LNode *)malloc(sizeof(LNode));
    head->next = NULL;
    for (int i = 0; i < n; ++i)
    {
        cin >> data;
        p = (LNode *)malloc(sizeof(LNode));
        p->data = data;
        p->next = head->next;
        head->next = p;
    }
    return head;
}

LNode *CreateList_Rear(int n) //创建链表尾插法
{
    ElemType data;
    LNode *head, *rear, *p;
    head = rear = (LNode *)malloc(sizeof(LNode));
    head->next = NULL;
    for (int i = 0; i < n; ++i)
    {
        cin >> data;
        p = (LNode *)malloc(sizeof(LNode));
        p->data = data;
        p->next = rear->next;
        rear->next = p;
        rear = p;
    }
    return head;
}

Status ListInsert(LNode *head, int pos, ElemType e) //在第pos位置前插入元素e
{
    LNode *p = head;
    int i = 0;
    while (!p && i < pos - 1)
    {
        p = p->next;
        ++i;
    }
    if (!p || i > pos - 1)
        return ERROR;
    LNode *s = (LNode *)malloc(sizeof(LNode));
    s->data = e;
    s->next = p->next;
    p->next = s;
    return OK;
}

Status ListDelete(LNode *head, int pos) //删除指定位置的元素
{
    LNode *p = head;
    int i = 0;
    while (!p && i < pos - 1)
    {
        p = p->next;
        ++i;
    }
    if (!(p->next) || i > pos - 1)
        return ERROR;
    LNode *q = p->next;
    p->next = q->next;
    free(q);
    return OK;
}

ElemType Get_Elem_pos(LNode *head, int pos) //按序查找
{
    int i = 0;
    LNode *p = head;
    while (!p && i < pos)
    {
        p = p->next;
        ++i;
    }
    if (!p || i > pos)
        return ERROR;
    return p->data;
}

LNode *Get_Elem_value(LNode *head, int e) //按值查找
{
    LNode *p = head;
    while (!p && p->data != e)
        p = p->next;
    return p;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值