algorithm to remove element from single linked list

In this algorithm we were not given with the head node but instead given with the node that is to be deleted.

Lets look at an example:

              --------------------------------------
Node        : 1->20  | 2->30  | 3->40  | 4->50  | 5
              --------------------------------------
Node Address: 10     | 20     | 30     | 40     | 50

And assume we want to remove 3rd element where you are given only the THIRD node that is to be deleted.
Output should be: 1,2,4,5

Since you do not have access to the head, change the given node_to_be_deleted in this manner:

                  --------------------------------------
Node            : 1->20  | 2->30  | 4->50  | 4->50  | 5
                  --------------------------------------
Node Address    : 10     | 20     | 30     | 40     | 50

Instead of deleting the 3rd node we are moving 4th node into 3rd node and ignoring 4th node.

	/**
	 * Remove element from SLL
	 * @param node element to be removed
	 */
	public void removeElement(Node node) {
		node.value = node.next.value;
		node.next = node.next.next;
	}
Advertisements
Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

Diabolical or Smart

Nitwit, Blubber, Oddment, Tweak !!

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey