链表

背景

链表是一种非常经典的数据结构,对链表的基本操作有“增”,“删”,“改”,“查”,“遍历”,“反转”等;

通过测试代码的方式能更好的理解链表的操作原理,以及将其运用到今后的代码开发中。

代码

链表反转(逆序)

#include<iostream>

using namespace std;

//---表结点定义
struct Node{
    int num;
    Node * next;
};

//---链表定义
class List{
    public:
        //----------------------------------------------------初始化
        List()
        {
            this->head = new Node();
        }
        ~List()
        {
        }
        //----------------------------------------------------头插,头结点不保存数据
        void push_front(int num)
        {
            Node * newNode = new Node();
            newNode->num = num;
            newNode->next = head->next;
            head->next = newNode;
        }
        //----------------------------------------------------遍历
        void print()
        {
            Node * tmp = head->next;
            while (tmp != NULL)
            {
                if (tmp->next == NULL)
                    printf("[%d]", tmp->num);
                else
                    printf("[%d]->", tmp->num);

                tmp = tmp->next;
            }
            printf("
");
            
            //---打印节点地址
            tmp = head->next;
            while (tmp != NULL)
            {
                if (tmp->next == NULL)
                    printf("[%p]", tmp);
                else
                    printf("[%p]->", tmp);

                tmp = tmp->next;
            }
            
        }
        //----------------------------------------------------逆序
        void reverse()
        {
            //------------------------从表头开始"头插"到新表
            Node * newNode = new Node();
            Node * p = newNode->next;
            Node * tmp = this->head->next;
            while (tmp != NULL)
            {
                Node * tmp_next = tmp->next;
                //--------------------将当前结点挂到新链表
                tmp->next = p;
                newNode->next = tmp;
                //--------------------更新新链表插入位置
                p = tmp;
                //--------------------当前结点指针后移
                tmp = tmp_next;
            }
            delete this->head;
            this->head = newNode;
        }
    private:
        Node * head;
};

//---链表测试
void demo()
{
    List list;
    for (int i = 0; i < 10; ++i)
    {
        list.push_front(i);
    }
    printf("****************逆序前*******************
");
    list.print();
    printf("
");

    list.reverse();
    printf("****************逆序后*******************
");
    list.print();
    printf("
");
}
int main()
{
    demo();
}

补充

这是我很久前写的代码了,因为注释写得太模糊,看了很久都没看懂,呵呵。

原文地址:https://www.cnblogs.com/orejia/p/12113179.html