链表的创建、查询、删除,插入;

链表(LinkList)是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针。


这里写图片描述

单链表数据结构
struct Node
{
     int  _data ;             // 数据
     struct Node* _next;     // 指向下一个节点的指针
}Node, *PLinkList;
//输出链表
void PrintList(PList head)
{
    Node* begin = head;
    while (begin != NULL)
    {
        cout<<begin->_data<<"->";
        begin = begin->_next;
    }

    cout<<"NULL"<<endl;
}

Node* _CreateNode(DataType x)
{
    Node* tmp = new Node;
    tmp->_data = x;
    tmp->_next = NULL;
    return tmp;
}
//插入链表
void PushBack(PList& head, DataType x)
{
    if(head == NULL)
    {
        head = _CreateNode(x);
    }
    else
    {
        Node* tail = head;
        while(tail->_next != NULL)
        {
            tail = tail->_next;
        }

        tail->_next = _CreateNode(x);
    }
}
//删除链表最后一个节点
void PopBack(PList& head)
{
    if (NULL == head)
    {
        return;
    }
    else
    {
        Node* tail = head;
        Node* p = head->_next; 
        while (NULL!=p->_next)
        {
            tail = p; 
            p = p->_next;
        }
        tail->_next = NULL;
    }
}

//链表的头插
void PushFornt(PList& head, DataType x)
{
    if(NULL == head)
    {
        head = _CreateNode(x);
    }
    else
    {
        Node *tail=_CreateNode(head->_data);
        tail->_next=head->_next;
        head->_next=tail;
        head->_data=x;
    }
}

//删除第一个链表节点
void PopFront(PList& head)
{
    if (NULL == head)
    {
        return;
    }
    else
    {
        Node *tail=head->_next;
        head->_data=head->_next->_data;
        head->_next = head->_next->_next;
        tail->_next = NULL;

    }
}
//链表的逆序
void PrintTailToHead(PList head)
{
    stack<Node*> s;
    Node* begin = head;
    while (begin != NULL)
    {
        s.push(begin);
        begin = begin->_next;
    }

    while(!s.empty())
    {
        cout<<s.top()->_data<<"->";
        s.pop();
    }
    cout<<endl;
}

//查找节点
Node* Find(PList head, DataType x)
{
    Node* tail = head;
    while (tail != NULL)
    {
        if (x == tail->_data)
        {
            return tail;
        }
        tail = tail->_next;
    }
    cout << "NULL" << endl;
    return NULL;
}
//删除节点
void Erase(PList& head, Node* n)
{
    Node* t = head;
    Node* p = head->_next;
    if (n == t)
    {
        PopFront(head);
    }
    else
    {
        while (p != NULL)
        {

            if (n == p)
            {
                t->_next = p->_next;
                p->_next = NULL;
                return;
            }
            t = t->_next;
            p = p->_next;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值