import java.util.Scanner;
/**
* Created by MOHIT on 24-01-2018.
*/
class node{
public int element;
public node link;
//constructor that accepts only element
node(int element) {
this.element = element;
this.link = null;
}
//constructor that accepts both link and element
node(int element, node link){
this.element = element;
this.link = link;
}
//method to update the element
void updateData(int element){
this.element = element;
}
//method to update or setup link
void updateLink(node link){
this.link = link;
}
//method to get the element from the node
int getElement(){
return this.element;
}
//method to get the next node
node getNextNode(){
return this.link;
}
}
class LL {
Scanner sc = new Scanner(System.in);
node head;
void insertAtStart(int number){
node newNode = new node(number);
if(head == null){
head = newNode;
} else {
newNode.updateLink(head);
}
head = newNode;
return;
}
void insertAtEnd(int element){
if(head == null){
this.insertAtStart(element);
return;
}
node current = this.head;
while(current.getNextNode() != null){
current = current.getNextNode();
}
node newNode = new node(element);
current.updateLink(newNode);
return;
}
void display(){
node current = this.head;
while(current!= null){
System.out.print(current.getElement());
if(current.getNextNode() != null){
System.out.print("-->");
}
current = current.getNextNode();
}
}
// deleting node with only that node pointer
public void deleteNode(node current){
if(current == null){
return;
}else{
// make a pointer to next node
node nextNode = current.getNextNode();
// copy deteils of next node to current node
current.updateData(nextNode.getElement());
current.updateLink(nextNode.getNextNode());
// delete next node
nextNode = null;
}
}
// deleting kth element from the end
void delete_kth_Element_End(int k){
node first = this.head;
node second = this.head;
for(int i=0; i < k; i++){
second = second.getNextNode();
}
while(second != null){
first = first.getNextNode();
second = second.getNextNode();
}
deleteNode(first);
}
}
public class LinkedList {
public static void main(String arg[]) {
System.out.println("Program to delete the kth element from the end of Linked List.");
LL l1 = new LL();
l1.insertAtEnd(1);
l1.insertAtEnd(2);
l1.insertAtEnd(3);
l1.insertAtEnd(4);
l1.insertAtEnd(5);
l1.insertAtEnd(6);
l1.insertAtEnd(7);
l1.insertAtEnd(8);
l1.display();
System.out.println("\\nThe linked list after deleting the 3rd node from the end is : ");
l1.delete_kth_Element_End(3);
l1.display();
}
}