Reputation: 5
Here i am trying to implement the basic operations of "Single Linked List". But only here i am facing only one problem that is, after adding elements, i.e.
al.add("Ravi");
al.add("Vijay");
al.add("Sanjay");
al.add("Ajay");
I am getting output as:
[]--------->For empty Linked list
[Ravi,Ravi,Vijay,Sanjay,Ajay]------>After adding elements.
class MyLinkedList {
private Node first;
private Node last;
private int count;
public void add(Object ele){
if(first==null){
first=new Node(ele);
last=first;
count++;
}
last.next=new Node(ele);
last=last.next;
count++;
}
public int size(){
return count;
}
public Object get(int index){
if(index>=size())throw new IndexOutOfBoundsException();
Node p=first;
for(int i=0;i<=index;i++){
p=p.next;
}
return p.ele;
}
public void remove(int index){
if(index>=size())throw new IndexOutOfBoundsException();
if(index==0){
first=first.next;
count--;
return;
}
}
@Override
public String toString() {
if(size()==0)return "[]";
Node p=first;
String s="[" + p.ele;
while(p.next!=null){
p=p.next;
s+=","+p.ele;
}
return s + "]";
}
private class Node{
Object ele;
Node next;
Node(Object ele){
this.ele=ele;
}
}
public static void main(String[] args) {
MyLinkedList al=new MyLinkedList();
System.out.println(al);
al.add("Ravi");
al.add("Vijay");
al.add("Sanjay");
al.add("Ajay");
System.out.println(al);
}
}
Upvotes: 0
Views: 448
Reputation: 1
In this method
public void add(Object ele){
if(first==null){
first=new Node(ele);
last=first;
count++;
}
last.next=new Node(ele);
last=last.next;
count++;
}
You have to return from the if statement as shown below, otherwise the first value will be inserted twice as the control will be transferred to the next statement after the execution of if block. You can also put the remaining code under the else block, it will also work.
public void add(Object ele){
if(first==null){
first=new Node(ele);
last=first;
count++;
return;
}
last.next=new Node(ele);
last=last.next;
count++;
}
Upvotes: 0
Reputation: 13652
In your method:
public void **add**(Object ele){
if(first==null){
first=new Node(ele);
last=first;
count++;
}
last.next=new Node(ele);
last=last.next;
count++;
}
You have to put a return
statement at the end of the if clause, or use else
. Else you add the first element twice.
Upvotes: 2
Reputation: 69440
Because you add it twice:
public void **add**(Object ele){
if(first==null){
first=new Node(ele); //First
last=first;
count++;
}
last.next=new Node(ele); //second.
last=last.next;
count++;
}
add an else Statement:
public void **add**(Object ele){
if(first==null){
first=new Node(ele);
last=first;
count++;
} else {
last.next=new Node(ele);
last=last.next;
count++;
}
}
Upvotes: 3