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

Join the forum, it's quick and easy

AndreiL
Welcome to AndreiL.
Enjoy your time.
Please log in.
AndreiL
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Simple linked list code

Go down

Simple linked list code Empty Simple linked list code

Post by Lucaci Andrei 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;}
};

Lucaci Andrei
Lucaci Andrei
"Tata Lor"
Simple linked list code 138

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

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