작성해본 링크드리스트
public class MySingleNode<T> {
public Node Head = null;
public class Node<T> {
T data;
Node<T> pointer;
public Node(T item) {
this.data = item;
}
}
public void addNode(T data) {
if (Head == null) {
Head = new Node<T>(data);
} else {
Node node = Head;
while (node.pointer != null) {
node = node.pointer;
}
node.pointer = new Node<T>(data);
}
}
public void printAll() {
if (Head != null) {
Node<T> node = this.Head;
System.out.println(node.data);
while(node.pointer != null) {
node = node.pointer;
System.out.println(node.data);
}
}
}
public Node<T> search(T data) {
if (this.Head == null) {
return null;
}
else {
Node<T> node = this.Head;
while (node != null) {
if (node.data == data) {
return node;
} else {
node = node.pointer;
}
}
return null;
}
}
public void addNodeInside(T data, T isData) {
Node<T> searchNode = this.search(isData);
if (searchNode == null) {
addNode(data);
} else {
Node<T> nextNode = searchNode.pointer;
searchNode.pointer = new Node<T>(data);
searchNode.pointer.pointer = nextNode;
}
}
public void MyDeleteNodeInside(T deleteData) {
if(this.Head == null) {
;
} else {
Node<T> node = this.Head;
while (node != null) {
if(node.pointer.data == deleteData) {
node.pointer = node.pointer.pointer;
break;
} else {
node = node.pointer;
}
}
}
}
public boolean delNode(T isData) {
if (this.Head == null) {
return false;
} else {
Node<T> node = this.Head;
if (node.data == isData) {
this.Head = this.Head.pointer;
return true;
} else {
while (node.pointer != null) {
if (node.pointer.data == isData) {
node.pointer = node.pointer.pointer;
return true;
}
node = node.pointer;
}
return false;
}
}
}
public static void main(String[] args) {
MySingleNode<Integer> myList = new MySingleNode<>();
myList.addNode(1);
myList.addNode(2);
myList.addNode(3);
myList.addNodeInside(5,2);
myList.delNode(3);
myList.printAll();
}
}