package linkedlist.singly; public class DeleteMiddleElementFromLinkList { Node startNode; public static void main(String[] args) { new DeleteMiddleElementFromLinkList(); } public DeleteMiddleElementFromLinkList() { Node temp1 = new Node(1); Node temp2 = new Node(2); Node temp3 = new Node(3); Node temp4 = new Node(4); Node temp5 = new Node(5); Node temp6 = new Node(6); Node temp7 = new Node(7); Node temp8 = new Node(8); temp1.setNext(temp2); temp2.setNext(temp3); temp3.setNext(temp4); temp4.setNext(temp5); temp5.setNext(temp6); temp6.setNext(temp7); temp7.setNext(temp8); startNode = temp1; System.out.println("Before::"); printLinkList(startNode); Node newStart = deleteMiddleElement(startNode); System.out.println("After::"); printLinkList(newStart); } private Node deleteMiddleElement(Node startNode) { if(startNode==null || startNode.getNext()==null){ //It contain only 1 element, so program assumption as that is the middle element as well. System.out.println("\nMiddle Element is:"+startNode.getData()); return null; } //Finding Middle Element. Node p1=startNode,p2=startNode; while(p2!=null && p2.getNext()!=null && p2.getNext().getNext()!=null){ p1 = p1.getNext(); p2 = p2.getNext().getNext(); } //p1 is at middle now. //say for example arr is 1 2 3 4 5, if p1 is at 3, now you have reference at 3, which need to be deleted, //say at one instance if you have access to previous element ie 2 then your task is done, ie at pointer 2, you can do pointerAt2.setNext(pointerAt2.getNext().getNext()) //but unfortunately, you don't have access to previous element, so now, we will create the same scenario and try to make 3 as our previous element. //At pointer 3, copy the data of next position ie 4 to pointer at place 3, so it will become 1 2 4 4 5. //Now, your pointer position is, //1 2 4 4 5 // p1 -----------------> now our situation is same as we have previous pointer, at this place we can do p1.setNext(p1.getNext().getNext()). //NOTE: if you have reference to last element to delete it, then it is not possible to delete it. System.out.println("\nMiddle Element is:"+p1.getData()); if(p1.getNext()!=null){ p1.setData(p1.getNext().getData()); p1.setNext(p1.getNext().getNext()); } return startNode; } private void printLinkList(Node startNode) { Node tempNode = startNode; while(tempNode!=null){ System.out.print(tempNode.getData() + " "); tempNode = tempNode.getNext(); } } }
Questions on Stack, Queues, Linkedlist, Binary Trees, Sorting, Searching, Graphs etc with solution using Java Language.
Sunday, 24 May 2015
Write a function to delete a node in the middle of a singly linked list.
Labels:
Linkedlist
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment