单链表逆置(C++)
来源:互联网 发布:win10系统开机优化 编辑:程序博客网 时间:2024/06/08 07:39
//结点类 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;}