This repository has been archived by the owner on Sep 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.java
114 lines (95 loc) · 2.17 KB
/
LinkedList.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
package com.hkt.tutorial.algorithms.ds;
@SuppressWarnings("unused")
public class LinkedList<T> {
private int size;
private Node head;
public LinkedList() {
}
public void add(Object data) {
if (head == null) {
head = new Node(data);
}
Node temp = new Node(data);
Node curr = head;
if (curr != null) {
while (curr.getNext() != null) {
curr = curr.getNext();
}
curr.setNext(temp);
}
size++;
}
private int getN() {
return size;
}
public void add(T data, int index) {
Node temp = new Node(data);
Node curr = head;
if (curr != null) {
for (int i = 0; i < index && curr.getNext() != null; i++) {
curr = curr.getNext();
}
}
temp.setNext(curr.getNext());
curr.setNext(temp);
size++;
}
public Object get(int index) {
if (index < 0)
return null;
Node curr = null;
if (head != null) {
curr = head.getNext();
for (int i = 0; i < index; i++) {
if (curr.getNext() == null)
return null;
curr = curr.getNext();
}
return curr.getData();
}
return curr;
}
public boolean remove(int index) {
if (index < 1 || index > size())
return false;
Node curr = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (curr.getNext() == null)
return false;
curr = curr.getNext();
}
curr.setNext(curr.getNext().getNext());
size--;
return true;
}
return false;
}
public int size() {
return getN();
}
private class Node {
Node next;
Object data;
public Node(Object dataValue) {
next = null;
data = dataValue;
}
public Node(Object dataValue, Node nextValue) {
next = nextValue;
data = dataValue;
}
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}