patternjavaModerate
Implementing a set using a linked list
Viewed 0 times
linkedusinglistimplementingset
Problem
My task is to add the specified element to the linked list if it is not already present
This is my solution
Can please anybody check it and correct if there are mistakes, or give hints to correct it?
/**
* Adds the specified element to this set if it is not already present.
* @param o element to be added to this set.
* @return true if this set did not already contain the specified element.
* @throws NullPointerException - if the specified element is null and this set does
not support null elements
*/This is my solution
public boolean add(E o) {
if (o == null)
throw new NullPointerException();
ListNode newNode = new ListNode(o, null);
if (contains(o))
{
return false;
}
else {
head.next=newNode;
head=newNode;
return true;
}
}Can please anybody check it and correct if there are mistakes, or give hints to correct it?
Solution
Let's say that you are starting with a list containing five elements:
$$
\newcommand{ptr}[1]{\overset{\mathtt{#1}}{\longrightarrow}}
\mathtt{head} \ptr{} \fbox{first} \ptr{next}
\fbox{second} \ptr{next}
\fbox{rest} \ptr{next}
\fbox{of} \ptr{next}
\fbox{list} \ptr{next} \mathtt{null}
$$
Then, you add a non-duplicate item called "another". After executing
$$
% "align" allows us to do vertical alignment
% "\\" separates lines
% "&" is an alignment marker. The markers in different rows
% are positioned above each other, and horizontally centered.
\newcommand{ptr}[1]{\overset{\mathtt{#1}}{\longrightarrow}}
\begin{align*}
&\mathtt{newNode} \\
&\quad\downarrow \\
\mathtt{head} \ptr{} \fbox{first} \ptr{next} &\fbox{another} \ptr{next} \mathtt{null} \\
&\fbox{second} \ptr{next}
\fbox{rest} \ptr{next}
\fbox{of} \ptr{next}
\fbox{list} \ptr{next}
\mathtt{null}
\end{align*}
$$
You've just orphaned and discarded everything starting from the second element. Then it gets worse when you set
$$
\newcommand{ptr}[1]{\overset{\mathtt{#1}}{\longrightarrow}}
\mathtt{head} \ptr{} \fbox{first} \ptr{next}
\fbox{second} \ptr{next}
\fbox{rest} \ptr{next}
\fbox{of} \ptr{next}
\fbox{list} \ptr{next} \mathtt{null}
$$
Then, you add a non-duplicate item called "another". After executing
head.next=newNode:$$
% "align" allows us to do vertical alignment
% "\\" separates lines
% "&" is an alignment marker. The markers in different rows
% are positioned above each other, and horizontally centered.
\newcommand{ptr}[1]{\overset{\mathtt{#1}}{\longrightarrow}}
\begin{align*}
&\mathtt{newNode} \\
&\quad\downarrow \\
\mathtt{head} \ptr{} \fbox{first} \ptr{next} &\fbox{another} \ptr{next} \mathtt{null} \\
&\fbox{second} \ptr{next}
\fbox{rest} \ptr{next}
\fbox{of} \ptr{next}
\fbox{list} \ptr{next}
\mathtt{null}
\end{align*}
$$
You've just orphaned and discarded everything starting from the second element. Then it gets worse when you set
head=newNode.Context
StackExchange Code Review Q#48679, answer score: 11
Revisions (0)
No revisions yet.