数据结构笔记(二)链表

#include<stdio.h>

#include<stdlib.h>

//单链表:带头结点或者不带头结点

给变量起一个别名,方便后面修改

typedef int E;

typedef struct ListNode * Node;

//结点

struct ListNode {

    E element;//存储的数据

    struct ListNode * next;//指向下一个结点的指针

};

//创建头结点

//变量指针

void initList(Node node)

{

    node->next=NULL;

}

//链表插入结点

//变量链表头结点,插入元素,插入位序

//时间复杂度O(n)

int insertList(Node head,E element,int index)

{

    //位序不符合插入失败

    if(index<1)

    {

        return 0;

    }

    while(index!=0)

    {

        head = head->next;

        //越界

        if(head==NULL)

        {

            return 0;

        }

        index--;

    }

    Node node = malloc(sizeof(struct ListNode));

    if(node==NULL)

    {

        //扩容失败

        return 0;

    }

    node->element=element;

    node->next=head->next;

    head->next=node;

}

//链表删除结点

//变量链表头结点,删除位序

//时间复杂度O(n)

int deleteList(Node head,int index)

{

    //位序不符合删除失败

    if(index<1)

    {

        return 0;

    }

    while(index!=0)

    {

        head = head->next;

        //越界

        if(head->next==NULL)

        {

            return 0;

        }

        index--;

    }

    Node timenode = head->next;

    head ->next = head->next->next;

    free(timenode);

}

//获取对应位置的元素

//变量链表头结点,查找位序

//时间复杂度O(n)

E getList(Node head,int index) 

{

    //位序不符合获取失败

    if(index<1)

    {

        return 0;

    }

    do

    {

        head = head->next;

        //越界

        if(head==NULL)

        {

            return 0;

        }

    }

    while(index!=0);

    return head->element;

}

//查找元素的位置

//变量链表头结点,查找的元素

int findList(Node head,E element)

{

    //计数器

    int i = 1;

    //走到第一个结点开始判断

    head = head->next;

    do

    {

        if(head->element==element)

        {

            return i;

        }

        head = head->next;

        i++;

    }

    while(head->next!=NULL);

    //未找到

    return 0;

}

//链表长度

//变量链表头结点

int sizeList(Node head)

{

    int i = 1;

    head = head->next;

    while(head!=NULL)

    {

        i++;

        head = head->next;

    }

    return i;

}

int main()

{

    //定义一个头结点指针(空的头结点)

    struct ListNode head;

    //创建头结点

    initList(&head);

}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值