Skip to content

Instantly share code, notes, and snippets.

@akashkumarcs19
Created March 3, 2021 17:11
Show Gist options
  • Save akashkumarcs19/3f2d66e32ad020da60231f5a34a53e19 to your computer and use it in GitHub Desktop.
Save akashkumarcs19/3f2d66e32ad020da60231f5a34a53e19 to your computer and use it in GitHub Desktop.
InsertionOnAParticularPositionInSL
class Node {
int data;
Node next;
Node(int data ){
next = null;
this.data = data;
}
}
public class PalLinkedList {
Node head;
public PalLinkedList(){
head = null;
}
public void add(int data){
Node new_node = new Node(data);
if(isEmpty()){
head = new_node;
}
else{
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = new_node;
new_node.next = null;
}
}
public void show(){
Node temp = head;
while(temp!= null){
System.out.println(temp.data);
temp = temp.next;
}
}
public boolean isEmpty() {
if (head == null)
return true;
else return false;
}
public int lengthOfList(){
int count = 0;
Node temp = head;
while(temp != null){
count+=1;
temp = temp.next;
}
return count;
}
public void insert(int data,int position){
Node temp = head;
Node new_node = new Node(data);
int count = 0;
if(position == 1){
new_node.next = temp;
head = new_node;
}
else if(lengthOfList() < position-1){
System.out.println(position+" "+"is Out of range");
return;
}
else if(temp == null)
head = new_node;
else{
count = 1;
while(count != position-1){
temp = temp.next;
count +=1;
}
temp.next = new_node;
temp = new_node;
new_node.next = temp.next;
}
}
public static void main(String[] args) {
PalLinkedList pl = new PalLinkedList();
pl.add(56);
pl.add(15);
pl.insert(2,1);
pl.insert(5,5);
pl.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment