单链表

1,单链表
单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。

链表中的数据是以节点来表示的,每个结点的构成:元素( 数据元素的映象) + 指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。

链表的结点结构:

┌───┬───┐

│data │next │

└───┴───┘

typedef struct Node
{
    int data;//数据域
    struct Node*next;//节点指针(下一个)
}Node,*List;//List===>>struct Node*

void InitList(List p)
{
    assert(p!=NULL);
    if(p->next==NULL)
    {
        return;
    }
    p->next=NULL;
}
static Node*GetNode(int val)        //设置新节点
{
    Node*pGet=(Node*)malloc(sizeof(Node));
    assert(pGet!=NULL);
    pGet->data=val;
    pGet->next=NULL;
    return pGet;
}
bool Insert_head(List p,int val)        //头插
{
    assert(p!=NULL);
    Node*pGet=GetNode(val);
    pGet->next=p->next;
    p->next=pGet;
    return true;
}
bool Insert_tail(List p, int val)     //尾插
{
    assert(p!=NULL);
    Node*pcur=p;
    for(;pcur!=NULL;pcur=pcur->next)
    {}
    Node*pGet=GetNode(val);
    pcur->next=pGet;
    return true;
}
bool Insert_pos(List p, int pos, int val)  //从pos位置插入
{
    Node*pcur=p;
    for(int i=0;i<=pos-1;i++)
    {
        pcur=pcur->next;
    }
    Ndoe*pGet=GetNode(val);
    pGet->next=pcur->next;
    pcur->next=pGet;
    return true;
}
int Getlength(List p)
{
    int count=0;
    Node*pcur=p->next;
    while(pcur!=NULL)
    {
        count++;
        pcur=pcur->next;
    }
    return count;
}
Node *Search_pre(List p, int key)
{
    Node*pcur=p;
    for(;pcur->next!=NULL;pcur=pcur->next)
    {
        if(pcur->next->data==key)
        {
            return pcur;
        }
    }
    return true;
}
bool Delete(List p, int key)
{
    Node*p1=Search_pre(p.key);
    if(p1==NULL)
    {
        return fasle;
    }
    Node*pDel=p1->next;
    p1->next=pDel->next;
    free(pDel);
    pDel=NULL;
    return true;
}
bool IsEmpty(List p)
{
    if(p->next==NULL)
    {
        return true;
    }
    return false;
}
void Show(List p)
{
    Node*pcur=p->next;
    while(pcur!=NULL)
    {
        printf("%d ",pcur->data);
    }
    printf("\n");
}
void Destroy(List p)
{
    Node*pDel=NULL;
    while(p->next!=NULL)
    {
        pDel=p->next;
        p->next=pDel->next;
        free(pDel);
    }
    pDel=NULL;
}
Node* reverse(List p)         //逆置
{
    assert(p!=NULL);
    Node*revhead=NULL;
    Node*prev=NULL;
    Node*pnode=p;
    while(pnode!=NULL)
    {
        Node*pnext=pnode->next;
        if(pnext==NULL)
        {
            revhead=pnode;
        }
        pnode->next=prev;
        prev=pnode;
        pnode=pnext;
    }
    return revhead;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值