#include <iostream>
#include<math.h>
using namespace std;
typedef int type;
typedef struct Node
{
type data;
Node *next;
} node;
node *head = NULL; //Đầu link
void show() {
node *ptr = head;
cout << "Du lieu trong Linked la:" << endl;
while (ptr != NULL)
{
cout << ptr->data << " ";
ptr = ptr->next;
}
cout << endl;
}
void insertFirst(type Item) {
node *link = new Node;
link->data = Item;
link->next = head;
head = link;
}
node* deleteFirst() {
node *temp = head;
head = head->next;
return temp;
}
/*Tính length của link*/
int length() {
int count = 0;
node *temp = head;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
/*Kiểm tra link trống*/
bool isEmpty() {
if (head == NULL)
return true;
return false;
}
/*Chèn một node vào link*/
void insert(int position, type Item) {
int size = length();
/*Cho link bắt đầu từ vị trí 1,2...*/
if (position > size || position < 1)
cout << "Vi tri khong hop le";
else if (position == 1)
insertFirst(Item);
else {
node *insertItem = new Node;
node *temp;
int count = 1;
temp = head;
/*Vì ta xem head có vị trí là 1 nên bắt đầu duyệt count = 1*/
while (count != position - 1) {
count++;
temp = temp->next;
}
insertItem->data = Item;
insertItem->next = temp->next;
temp->next = insertItem;
}
}
void Delete(int position) {
int size = length();
if (position < 0 || position > size)
cout << "Vi tri khong hop le";
else if (position == 1)
deleteFirst();
else {
int count = 1;
node *temp, *p;
temp = head;
while (count != position - 1) {
count++;
temp = temp->next;
}
p = temp->next;
p = p->next;
temp->next = p;
}
}
int main() {
insertFirst(5);
insertFirst(6);
insertFirst(7);
insert(1, 12);
insert(4, 17);
show();
Delete(5);
Delete(4);
show();
}