Think we have to design Singly Linked List :
What should come into our mind ???????????
Linked List will have value field and reference to next node field.
Structure Definition of a node in a Singly Linked List :
// Definition for singly Linked List
public class SinglyListNode {
int val;
SinglyListNode next;
SinglyListNode(int x){
val = x;
}
}
Initiate a new Linked List : Represent a linked list using the head node.
class MyLinkedList {
private SinglyListNode head;
public MyLinkedList(){
head = null;
}
}
Traverse the linked list to get element by index.
private SinglyListNode getNode(int index){
SinglyListNode cur = head;
for(int i =0 ; i < index && cur != null ; ++i){
cur = cur.next;
}
return cur;
}
//Function to return last element of the List.
private SinglyListNode getTail(){
SinglyListNode cur = head;
while(cur !=null && cur.next !=null){
cur = cur.next;
}
return cur;
}
// Function to return value of index-th node in the linked list.
private int get(int index){
SinglyListNode cur = head;
for(int i =0 ;i < index && cur != null ; ++i){
cur = cur.next;
}
return cur == null ? -1 : cur.val;
}
// Function to add a new Node.
// Here adding the node before the first element.
public void addAtHead (int val){
SinglyListNode cur = new SinglyListNode(val);
cur.next = head;
head = cur;
return;
}
// Here adding a node to the last element of the linked list.
public void addAtTail(int val){
SinglyListNode cur = new SinglyListNode(val);
if(head == null){
cur.next = head;
head = cur;
return;
}
SinglyLinkedNode dummy = head;
while(dummy.next !=null){
dummy = dummy.next;
}
dummy.next = cur;
}
// Add at particular index and the val.
public void addAtIndex(int val , int index){
SinglyListNode cur = new SinglyListNode(val);
if(index == 0){
cur.next = head;
head = cur;
return;
}
SinglyListNode prev = getNode(index-1);
if(prev == null){
return;
}
SinglyListNode next = prev.next;
cur.next = next;
prev.next = cur;
}
Delete a Node :
public void deleteIntIndex(int index){
SinglyListNode cur = getNode(index);
if(cur == null){
return;
}
SinglyListNode prev = getNode(index-1);
SinglyListNode next = cur.next;
if(prev != null){
prev.next = next;
} else {
head = next;
}
}
public void addAtTail(int val){
SinglyListNode cur = new SinglyListNode(val);
if(head == null){
cur.next = head;
head = cur;
return;
}
SinglyLinkedNode dummy = head;
while(dummy.next !=null){
dummy = dummy.next;
}
dummy.next = cur;
}
// Add at particular index and the val.
public void addAtIndex(int val , int index){
SinglyListNode cur = new SinglyListNode(val);
if(index == 0){
cur.next = head;
head = cur;
return;
}
SinglyListNode prev = getNode(index-1);
if(prev == null){
return;
}
SinglyListNode next = prev.next;
cur.next = next;
prev.next = cur;
}
Delete a Node :
public void deleteIntIndex(int index){
SinglyListNode cur = getNode(index);
if(cur == null){
return;
}
SinglyListNode prev = getNode(index-1);
SinglyListNode next = cur.next;
if(prev != null){
prev.next = next;
} else {
head = next;
}
}