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;
	}

3 Responses to algorithm to remove element from single linked list

  1. you haven’t addressed the case where node.next is null (i.e. delete the last node)

  2. PK Jajara says:

    As the solution above doesn’t work if the node to be removed is *last* node in linked list, following check has to be added:

    if (node == null || node.next == null){
    return false;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

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

%d bloggers like this: