(链表)链表倒序

  链表倒序,难点在于如何一个个地修改。虽然不是数组,但是大概思想是一样的,所以可以用一个for循序,一个游标对应for循环里面的 i,只不过要记得前一个节点和后一个节点,尤其是后一个,因为修改之后就访问不到后面的,所以要记录。for每一个循环只改变所指向的那个节点的指针,这样既不会乱套了。

  用一个for循环就非常好理解了,之前用while把我自己都搞晕电脑了。。。

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

//链表节点类
class Node
{
private:
    int m_data;
    Node* m_next;

    Node(Node&) {}        //copy constructor is not allowed

public:
    explicit Node(int val = 0) : m_data(val), m_next(NULL) {}
    int getData() const { return m_data; }
    void setData(int val) { m_data = val; }
    Node* getNext(void) const { return m_next; }
    void setNext(Node* p) { m_next = p; }
};

//链表
class MyList
{
private:
    Node* m_head;    //pionter to the first node of the list
    Node* m_tail;    //poinoer to the last node of the list

    MyList(MyList&) {}
public:
    explicit MyList() : m_head(NULL), m_tail(NULL) {}
    void addNode(Node* pNode);
    void show(void) const;
    void reverse(void);
    void clean(void);
};

void MyList::addNode(Node* pNode)
{
    if (m_head)
    {
        m_tail->setNext(pNode);
        m_tail = pNode;
    }
    else        //blank list
    {
        m_head = pNode;
        m_tail = pNode;
    }
}

void MyList::show(void) const
{
    Node* pNode = m_head;
    while (pNode)
    {
        std::cout << pNode->getData() << "    ";
        pNode = pNode->getNext();
    }
}

void MyList::reverse(void)
{
    Node* preNode = NULL;        //下面游标的前一个
    Node* pNode ;        //指向每一个节点,相当于游标
    Node* afterNode;        //上面游标的上一个

    for (pNode = m_head; pNode != NULL; pNode = afterNode)    //这里的每次循环对应一个节点,本质上和数组原理差不多
    {
        afterNode = pNode->getNext();
        pNode->setNext(preNode);
        preNode = pNode;
    }

    pNode = m_head;    //交换头尾指针
    m_head = m_tail;
    m_tail = pNode;
}

void MyList::clean(void)
{
    if (m_head)
    {
        Node* pNode = m_head;
        Node* pTemp;
        while (pNode)
        {
            pTemp = pNode->getNext();
            delete pNode;
            pNode = pTemp;
        }

        m_head = m_tail = NULL;
    }
}

int main(void)
{
    MyList listHead;

    srand((unsigned)time(NULL));
    for (int i = 0; i < 9; i++)
    {
        int temp = rand() % 50;
        Node* pNode = new Node(temp);
        listHead.addNode(pNode);
    }
    listHead.show();

    listHead.reverse();
    cout << endl;
    listHead.show();
    listHead.clean();
    listHead.show();
    
    system("pause");
}

 

 

转载于:https://www.cnblogs.com/jiayith/p/3849591.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值