Mã: // linkedList.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include "assert.h" using namespace std; template <class Item> class LinkedList { private: Item data; LinkedList* next; public: LinkedList (); void setValue (Item &x); void setNext (LinkedList *newNext); Item getValue (); LinkedList* getNext (); LinkedList* element (int i); void print (); int length (); LinkedList* insert (int i, Item &x); LinkedList* del (int i); void append (Item &x); Item Max (); }; template <class Item> LinkedList<Item>::LinkedList () { next = NULL; } template <class Item> void LinkedList<Item>::setValue (Item &x) { data = x; } template <class Item> void LinkedList<Item>::setNext (LinkedList *newNext) { next = newNext; } template <class Item> Item LinkedList<Item>::getValue () { return data; } template <class Item> LinkedList<Item>* LinkedList<Item>::getNext () { return next; } template <class Item> void LinkedList<Item>::print () { cout << data << " "; if (next != NULL) next->print (); else cout << endl; } template <class Item> int LinkedList<Item>::length () { LinkedList<Item> *currentNode = this; int len = 0; while (currentNode != NULL) { len++; currentNode = currentNode->getNext (); } return len; } template <class Item> LinkedList<Item>* LinkedList<Item>::element (int i) { int index = 0; LinkedList<Item> *current = this; while (index < i && current != NULL) { index ++; current = current ->getNext (); } return current; } template <class Item> LinkedList<Item>* LinkedList<Item>::insert (int i, Item &x) { assert ( i >=0 && i <= length ()); LinkedList<Item>* q; q = new LinkedList<Item>; q->setValue (x); if (i == 0) { q->setNext (this); return q; } else { LinkedList<Item>* pre = element (i - 1); LinkedList* p = pre->getNext (); pre->setNext (q); q->setNext (p); return this; } } template <class Item> LinkedList<Item>* LinkedList<Item>::del (int i) { assert ( i >=0 && i < length ()); if (i == 0) return next; else { LinkedList<Item>* pre = element (i - 1); LinkedList* p = pre->getNext (); pre->setNext (p->next); return this; } } template <class Item> void LinkedList<Item>::append (Item &x) { LinkedList<Item> * tail; tail = new LinkedList<Item>; tail = element (length () - 1); LinkedList<Item>* q; q = new LinkedList<Item>; q->setValue (x); tail->setNext (q); } int _tmain(int argc, _TCHAR* argv[]) { LinkedList<int> *head = NULL; cout << head << endl; head = new LinkedList<int>; cout << head << endl; int headValue = 1; head->setValue (headValue); cout << "head's value: " << head->getValue () << endl; int value = 2; //insert vào đầu danh sách head = head->insert (1, value); int val3 = 3; head->append (val3); head->del (0); head->print (); cout << "Length: " << head->length () << endl; LinkedList<int> *p; p = head ->element (0); cout << "p0's value: " << p->getValue () << endl; return 0; }