public class LinkedList<T> {
Node<T> headNode = null;
Node<T> tailNode = null;
int count = 0;
public LinkedList() {
// TODO Auto-generated constructor stub
tailNode = headNode = new Node<T>();
headNode.element = null ;
}
void insertAtHead(T element) {
Node<T> tempNode = new Node<>();
tempNode.element = element;
tempNode.next = headNode.next;
headNode.next = tempNode;
if (count == 0) {
tailNode = tempNode;
}
count++;
}
void insertAtTail(T element) {
Node<T> tempNode = new Node<>();
tempNode.element = element;
tempNode.next = null;
tailNode.next = tempNode;
tailNode = tempNode;
count++;
}
static void display(LinkedList<?> linkedList) {
if (linkedList.count != 0) {
Node<?> iteratorNode = linkedList.headNode.next;
while(iteratorNode!=null) {
System.out.println(iteratorNode.element);
iteratorNode = iteratorNode.next;
}
}
}
boolean contains(T key) {
boolean res = false;
if (count != 0) {
Node<T> iteratorNode = headNode.next;
while(iteratorNode!=null) {
if (iteratorNode.element.equals(key)) {
res = true;
break;
}
iteratorNode = iteratorNode.next;
}
}
return res;
}
boolean remove(T key) {
boolean res = false;
if (count != 0) {
Node<T> preNode = headNode;
Node<T> curNode = headNode.next;
for (;curNode != null;curNode = curNode.next) {
if (curNode.element.equals(key)) {
preNode.next = curNode.next;
res = true;
break;
}
preNode = preNode.next;
}
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<String> ll = new LinkedList<>();
ll.insertAtHead("abc");
ll.insertAtTail("zxy");
ll.insertAtHead("qwe");
ll.insertAtTail("gfg");
ll.insertAtHead("232");
ll.insertAtTail("!@#");
LinkedList.display(ll);
System.out.println(ll.contains("!@#"));
System.out.println(ll.remove("!@#"));
System.out.println(ll.contains("!@#"));
}
}
class Node<T> {
T element;
Node<T> next;
}