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

来源:互联网 发布:airplay怎么手机连mac 编辑:程序博客网 时间:2024/05/29 10:17

链表(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;        }    }}
0 0
原创粉丝点击