// Example program
#include <iostream>
#include <string>
using namespace std ;
template <class E>
struct Node
{
E element ; // lưu giá trị
Node<E> *next; // con trỏ để lưu địa chỉ node sau/kế
Node( E v = E() , Node<E>* n = 0):element(v),next(n){}
};
template <class E>
class SList{
protected:
int size ; // số lg phần tử hiện tại
Node<E> * head; // Con trỏ để lưu địa chỉ Node đầu tiên
public:
SList(){
this -> size = 0 ;
this -> head = nullptr ;
}
void print() const{
Node<E> * tmp = head ; // Biến tạm đi qua tất cả các node
while( tmp != nullptr ) {
cout << tmp -> element <<" ";
tmp = tmp->next;
}
cout <<endl;
}
void addFirst(E value) {
// B0: Khởi tạo Node với giá trị value
Node<E> * u = new Node<E> (value) ;
// B1: nối newNode -> node đầu hiện tại
u -> next = head ; // Do địa chỉ node đầu tiên dang
// ở head
// B2: Nối head đến newNode
head = u ;
size++;
}
void removeFirst() {
Node<E>* tmp = head ; // Chứa node đầu cần giải phóng
head = head -> next ; // Nối head đến node thứ 2
delete tmp ; // Giải phóng node đầu cũ
size--;
}
// O(size)
// Lay ra gia tri tai vi tri thu index
E getElement(int index) {
if ( index < 0 or index > size )
return E() ;
// head[5]
Node<E> *tmp = head ; // Mang nhiem vu duyet qua lan luot cac node o trong ds
int cnt = 0 ; // dem la da duyet duoc bao nhieu Node
while( tmp != nullptr) {
if ( cnt == index) // Neu da duyet den vi tri thu index => dung lai
return tmp -> element ;
cnt++;
tmp = tmp -> next ;
}
}
// O(size)
// Lieu ap dung tim kiem nhi phan vao SList co duoc khong ?
bool find(E value) const{
Node<E> *tmp = head ; // Mang nhiem vu duyet qua lan luot cac node o trong ds
while( tmp != nullptr) {
if ( tmp -> element == value)
return true;
tmp = tmp -> next ;
}
return false;
}
// chen vao vi tri thu index
void add (int index, E value) {
if ( index == 0 ) {
addFirst(value);
return ;
}
// Buoc 1: Tao Node u voi value
Node <E> * u = new Node<E> (value);
Node<E> * tmp = head ;
// Buoc 2: Duyet den vi tri thu index - 1
for ( int i = 0; i < index - 1 ; i++)
tmp= tmp-> next ;
// Buoc 3: Noi u voi index
u -> next = tmp -> next;
// Buoc 4: Noi index - 1 voi u
tmp-> next = u ;
// Buoc 5: size++;
size++;
}
void remove( int index) {
Node<E> * tmp = head ;
// Buoc 2: Duyet den vi tri thu index - 1
for ( int i = 0; i < index - 1 ; i++)
tmp= tmp-> next ;
// Buoc 3: Tao Node de luu node hien tai
Node<E> * old = tmp -> next;
// Buoc 4: Noi Node i - 1 den Node i + 1
tmp -> next = old -> next ;
delete old;
size--;
}
};
int main()
{
SList<int> s1;
s1.addFirst(10) ; // 10
s1.addFirst(9) ; // 9 10
s1.addFirst(11) ; // 11 9 10
s1.addFirst(7) ; //7 11 9 10
s1.print();
cout << s1.getElement(-1) <<endl;
cout << s1.find(8) <<endl;
s1.add(1, 20) ; // 7 20 11 9 10
s1.print();
s1.add(5, 100) ; // 7 20 11 9 10 100
s1.print();
s1.remove(1); // 7 11 9 10 100
s1.print();
s1.remove(3); // 7 11 9 100
s1.print();
}