作业三——反转链表

题目

用代码实现反转链表,要求:不能使用栈数据结构,时间复杂度O(n).

实现

  • LinkList.h文件代码
#ifndef _LINKLIST_H_
#define _LINKLIST_H_

// 节点类, 使用了模板类,方便数据类型
template<class T>
class Node
{
public:
    T data;
    Node<T>* next;
public:
    Node(){}
    Node(T v, Node<T>* node)
    {
        this->data = v;
        this->next = node;
    }
};

template<class T>
class LinkList
{
private:
    Node<T>* head;
    Node<T>* tail;
    int count;
public:
    LinkList();
    ~LinkList();
    int size();
    void print();
    void append(T data);
    void reverse();
};

// 初始化链表
template<class T>
LinkList<T>::LinkList() : count(0)
{
    head = new Node<T>;
    head->next = NULL;
    tail = head;
    int length;
    cout << "请输入链表初始长度:";
    cin >> length;
    for (int i = 0; i < length; ++i)
    {
        T data;
        cout << "第" << (i + 1) << "个节点的内容:";
        cin >> data;
        append(data);
    }
}

template<class T>
LinkList<T>::~LinkList()
{
    Node<T>* node = head->next;
    Node<T>* tmp;
    while (node != NULL)
    {
        tmp = node;
        node = node->next;
        delete tmp;
    }
    delete head;
    head = NULL;
    tail = NULL;
}

// 返回链表的长度
template<class T>
int LinkList<T>::size()
{
    return count;
}

template <class T>
void LinkList<T>::print()
{
    Node<T>* node = head->next;
    while (node)
    {
        cout << node->data << "  ";
        node = node->next;
    }
    cout << endl;
}

template <class T>
void LinkList<T>::append(T data)
{
    Node<T>* node = new Node<T>();
    node->data = data;
    node->next = NULL;
    tail->next = node;
    tail = node;
    ++count;
}

template <class T>
void LinkList<T>::reverse()
{
    // 由于是带有头节点的链表,因此需要这两个条件
    if (head->next == NULL || head->next->next == NULL)
        return;
    Node<T>* current = head->next->next;
    tail = head->next;
    tail->next = NULL;
    while (current)
    {
        Node<T>* tmp = current->next;
        current->next = head->next;
        head->next = current;
        current = tmp;
    }
}
#endif
  • main.cpp
#include <iostream>
#include "LinkList.cpp"
using namespace std;

int main()
{
    LinkList<int> list = LinkList<int>();
    cout << "链表结构内容:";
    list.print();
    list.reverse();
    cout << "链表反转后的结构:";
    list.print();
    system("pause");
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,735评论 0 3
  • 入职月余,总结出来了所谓的项目主管所做的工作 就目前来看,就两项。 第一,用印。品种也算丰富多样,债转协议,债转通...
    34号先生阅读 590评论 0 0
  • 少年,请大步向前,现在你所付出的一切,以后终将得到回报。 少年,请大步向前,想想以前被你遗忘了的理想。 少年,请大...
    Jay_Zhang阅读 318评论 0 1
  • 别人家的小班都是送一两次水,你家的孩子连续一周都有水; 别的姑娘来大姨妈都需要休息,你却日行万步去照顾小大一。 我...
    云一莫阅读 358评论 0 2
  • 01 “手机快没电了,身上一分钱都没有,肚子好饿,何解?” 八点六分的时候,小兰发了一条说说。我是八点十分看到的,...
    穆念晴阅读 726评论 1 45