/
MyLinkedList.cs
134 lines (99 loc) · 3.17 KB
/
MyLinkedList.cs
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
using System;
using System.Collections.Generic;
using System.Collections;
namespace algorithms {
class MyLinkedList<T>{
public MyNode<T> head { get; set; }
public MyLinkedList(){
this.head = null;
}
public void Add(T value){
MyNode<T> newNode = new MyNode<T>(value);
newNode.next = this.head;
this.head = newNode;
}
public int Size(){
MyNode<T> current = this.head;
int count = 0;
while(current != null){
count++;
current = current.next;
}
return count;
}
public MyNode<T> getFirst(){
return this.head;
}
public MyNode<T> getLast (){
MyNode<T> current = this.head;
while(current.next != null){
current = current.next;
}
return current;
}
public void Clear(){
this.head = null;
}
public void RemoveFirst(){
this.head = this.head.next;
}
public MyNode<T> RemoveLast (){
MyNode<T> current = this.head;
MyNode<T> temp = this.head;
if(this.head != null){
if(this.head.next == null){
this.head = null;
} else {
while(current.next.next != null){
current = current.next;
}
temp = current.next;
current.next = null;
}
}
return temp;
}
public void InsertLast (T data){
MyNode<T> current = this.head;
MyNode<T> newData = new MyNode<T>(data);
if(this.head != null){
if(this.head.next == null){
this.head.next = newData;
} else {
while(current.next.next != null){
current = current.next;
}
current.next = newData;
}
}
}
public MyNode<T> GetAt(int index){
int count = 1;
MyNode<T> current = this.head;
while(count < index && current != null){
current = current.next;
count++;
}
return current;
}
public void RemoveAt(int index){
if(this.head != null){
MyNode<T> beforeRemove = this.GetAt(index -1);
if(index == 0){
RemoveFirst();
} else if(beforeRemove != null && beforeRemove.next != null){
beforeRemove.next = beforeRemove.next.next;
}
}
}
public override string ToString(){
MyNode<T> current = this.head;
string result = "";
while(current != null){
result += current.data + ", ";
current = current.next;
}
return result;
}
}
}