-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyLinkedList.java
128 lines (106 loc) · 2.6 KB
/
MyLinkedList.java
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
package com.technocerry.linkedlist;
/**
* Created by robby.pontas on 6/1/15.
*/
public class MyLinkedList <T>{
private Node head;
private int size;
public MyLinkedList(){
head = new Node(null);
size = 1;
}
/**
*@param data data of linked list, can be any of object
*/
public void add(T data)
{
Node temp = new Node(data);
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(temp);
size++;
}
/**
*
* @param index index of data, start from 1, first next
* @return object as you created
*/
public T get(int index)
{
if (index <= 0 || index > size)
throw new IllegalArgumentException(index > size?"index out of range":"index must be greater than 0");
Node current = head.getNext();
for (int i = 1; i < index; i++) {
if (current.getNext() == null)
return null;
current = current.getNext();
}
return current.getData();
}
/**
*
* @param index index of data, start from 1, first next
* @return true if remove wa succeed
*/
public boolean remove(int index)
{
if (index < 1 || index > size)
return false;
Node data = head;
for (int i = 1; i < index; i++) {
if (data.getNext() == null)
return false;
data = data.getNext();
}
data.setNext(data.getNext().getNext());
size--;
return true;
}
/**
*
* @return size of datas
*/
public int size()
{
return size;
}
/**
*
* @return get all datas separated by comas
*/
public String toString() {
Node current = head.getNext();
String string = "";
while (current != null) {
string += current.getData().toString() + ", ";
current = current.getNext();
}
return string;
}
private class Node {
Node next;
T data;
public Node(T data) {
next = null;
this.data = data;
}
public Node(T data, Node next) {
this.next = next;
this.data = data;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}