Skip to content

Instantly share code, notes, and snippets.

@Mahdhir
Created May 2, 2020 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mahdhir/cbdff40c0475e94244fa4d5c652462dc to your computer and use it in GitHub Desktop.
Save Mahdhir/cbdff40c0475e94244fa4d5c652462dc to your computer and use it in GitHub Desktop.
A sample implementation of a Linked List with basic operations in Java
/**
*
* @author Mahdhi
*/
public class LinkedList{
Node head; // head of list
public LinkedList(){
head=null;
}
public boolean isEmpty(){
return head==null;
}
public void insertAtBeginning(int new_data) {
// insert the data
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public void insertAtEnd(int new_data) {
Node new_node = new Node(new_data);
if (head == null) {
head = new Node(new_data);
return;
}
new_node.next = null;
Node last = head;
while (last.next != null)
last = last.next;
last.next = new_node;
return;
}
public void insertAfter(Node prev_node, int new_data) {
if (prev_node == null) {
System.out.println("The given previous node cannot be null");
return;
}
Node new_node = new Node(new_data);
new_node.next = prev_node.next;
prev_node.next = new_node;
}
public Node search(int key){
Node temp = head;
while(temp != null){
if(temp.key == key){
return temp;
}
temp = temp.next;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment