Question: (In java) Create a method to delete a node at a particular position in the linked list AND Create a method to insert a node
(In java)
Create a method to delete a node at a particular position in the linked list AND
Create a method to insert a node at the tail/end of a linked list.
I have these methods that should be manipulated to achieve the methods above:
- Method for inserting a node at a particular position:
public listnodes insertAtPosition(listnodes head,int data,int position){ listnodes newnode=new listnodes(data,null);//create the newnode listnodes previous=head; int count=1;
while(count<=position-1) {//reach to a particular position count //when the condition is false, position is found listnodes current=previous.link; newnode.link=current; previous.link=newnode; return head; } - Method to delete the last node in a linked list: public listnodes deletelast(listnodes head){ listnodes cur=head; listnodes previouscur=head; while(cur.link!=null){//traverse till the last node previouscur=cur; cur=cur.link; } previouscur.link=null;//disconnect the last node return cur; } - Method to insert a node at the beginning of a linked list: public listnodes insertnode(int data,listnodes head){ //create a new node to be added in the beginning of the linked list listnodes newnode=new listnodes(data,null); //link the new node to the head node newnode.link=head; //make the new node as the front node head=newnode; return head; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
