Created
May 2, 2020 08:55
-
-
Save Mahdhir/cbdff40c0475e94244fa4d5c652462dc to your computer and use it in GitHub Desktop.
A sample implementation of a Linked List with basic operations in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @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