Linked List Class
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
#include <iostream>
using namespace std;
struct item{
int num;
item* nxt;
};
class LinkedList{
private:
item* head;
item* tail;
public:
LinkedList(){
head = NULL;
tail = NULL;
}
void insert(int x){
item *N = new item; //create item
N->num = x; //assign the number
N->nxt = NULL; //point it to nxt
if(head == NULL) //nothing in the list
{
head = N;
tail = N;
return;
}
item* ptr = head;
while(ptr->nxt)
ptr = ptr->nxt;
ptr->nxt = N;
return;
}
void printList(){
item* ptr = head;
cout << endl;
while(ptr){
cout << ptr->num << "->";
ptr = ptr->nxt;
}
cout << endl;
}
void reverse(){
item * rev = head->nxt;
item* R = rev->nxt;
tail = head;
head->nxt = NULL;
while(rev)
{
rev->nxt = head;
head = rev;
rev = R;
if(R)
R=R->nxt;
}
cout << "Reversed Below:" << endl;
printList();
}
void deleteItem(int x){
item* d = head;
item* b = d->nxt;
if(head->num == x)//if its at head;
{
head = head->nxt;
delete d;
return;
}
while(b->num != x)
{
d=d->nxt;
b=b->nxt;
}
d->nxt = b->nxt;
delete b;
d = NULL;
delete d;
printList();
return;
}
};
int main() {
LinkedList B;
B.insert(8);
B.insert(7);
B.insert(1);
B.insert(56);
B.insert(82);
B.insert(71);
B.printList();
B.reverse();
B.reverse();
B.deleteItem(56);
return 0;
}
Cpp
INFO