单链表逆置(C++)

//结点类 
template <typename T>
class Node
{
    public:
    Node()
    {
        ;
    }
    Node(const T &x)
    {
        data = x;
    }
    ~Node()
    {
        ;
    }
    T data;
    Node<T> *next;
};



//链表头文件
#include "Node.h"
template <typename T>
class LinkedList
{
    public:
    LinkedList()
    {
        head = new Node<T>();
        head->next = NULL;
    }
    ~LinkedList()
    {
        if (head)
        {
            delete head;
        }
    }
    void Append(const T&);
    bool Insert(int, const T&);
    bool Delete(int);
    bool Reverse();
    void Display() const;
    private:
    Node<T> *head;
};
#include "LinkedList.cpp"




//链表源文件
using namespace std;
template <typename T>
void LinkedList<T>::Append(const T &x)
{
    Node<T> *p = head;
    while (p->next)
    {
        p = p->next;
    }
    Node<T> *temp = new Node<T>(x);
    temp->next = NULL;
    p->next = temp;
}
template <typename T>
bool LinkedList<T>::Insert(int k, const T &x)
{
    int i = 0;
    Node<T> *p = head;
    while (i < k && p)
    {
        ++i;
        p = p->next;
    }
    if (p)
    {
        Node<T> *temp = new Node<T>(x);
        temp->next = p->next;
        p->next = temp;
        return true;
    }
    return false;
}
template <typename T>
bool LinkedList<T>::Delete(int k)
{
    int i = 0;
    Node<T> *p = head;
    while (i < k && p)
    {
        ++i;
        p = p->next;
    }
    if (p)
    {
        Node<T> *temp = p->next;
        p->next = temp->next;
        delete temp;
    }
    return true;
}
template <typename T>
bool LinkedList<T>::Reverse()
{
    Node<T> *p, *q, *r;
    p = head->next;
    q = p->next;
    p->next = NULL;
    while (q)
    {
        r = q->next;
        q->next = p;
        p = q;
        q =r;
    }
    head->next = p;
    return true;
}
template <typename T>
void LinkedList<T>::Display() const
{
    Node<T> *p = head->next;
    while (p)
    {
        cout << p->data << " ";
        p = p->next;
    }
}



//main函数
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main(void)
{
    LinkedList<int> *ll = new LinkedList<int>();
    for (int i = 0; i < 10; ++i)
    {
        ll->Append(i);
    }
    ll->Display();
    cout << endl;
    ll->Reverse();
    ll->Display();
    cout << endl;
    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值