AndreiL
Welcome to AndreiL.
Enjoy your time.
Please log in.

Simple linked list code

Go down

Simple linked list code

Post by Lucaci Andrei on Wed Jan 23, 2013 9:33 pm

Here's a simple and quick example of a linked list.

  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
* linkedlist.cpp
* linkedlist.cpp is licensed under GNU GENERAL PUBLIC LICENSE
* Created on: Jan 24, 2013
* Author: sin
*/

#include <iostream>
using namespace std;
template <class T>
class ll {
typedef struct node{
T elem;
node* link;
}node;
node* head;
int size;
public:
ll(){
head = new node;
head->link = NULL;
size=0;
}

void add(T elem){
if (size==0){head->elem = elem;size++;return;}
node* cur = head;
while(cur->link != NULL){
cur = cur->link;
}
cur->link = new node;
cur->link->elem = elem;
cur->link->link = NULL;
size++;
}

void removeHead(){
if (size==0) return;
node* cur = head->link;
delete head;
head = cur;
size--;
}

void removeAll(){
if (size==0)return;
if (head == NULL) return;
while (head != NULL){
removeHead();
}
}

void removeElem(T elem){
if (size==0) return;
node* p = head;
if (p->elem == elem){removeHead();return;}
if (p->link == NULL) return;
node* cur = p->link;
while (cur != NULL){
if (cur->elem == elem){
p->link = cur->link;
delete cur;
break;
}
p = cur;
cur = cur->link;
}
}

void removeT(){
if (size == 0) return;
node* p = head;
if (p == NULL) return;
node* cur = p->link;
if (cur == NULL) {delete p; size--;return;}
while (cur!=NULL){
p = cur;
cur = cur->link;
}
p->link = NULL;
delete cur;
size--;
}

bool isEmpty(){
return size == 0;
}

void printL(){
if (size==0) return;
node* cur = head;
while (cur != NULL){
cout<<cur->elem<<" ";
cur = cur->link;
}
}

T* toArray(T stop){
//stop is the end of the array. When it hits stop, you have ended your array of elements.
if (size==0) return NULL;
T* array = new T(size);
node* cur = head;
int index = 0;
while (cur != NULL){
array[index++] = cur->elem;
cur = cur->link;
}
array[size] = stop;
return array;
}

int getSize(){return size;}
};

avatar
Lucaci Andrei
"Tata Lor"


Number of messages : 222
Points : 2266743
Reputation : 1007
Registration date : 2008-08-15
Age : 26
Location : Cluj-Napoca

View user profile http://www.andreil.wgz.ro

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum