Results 1 to 3 of 3
- 04-11-2010, 05:10 PM #1
Member
- Join Date
- Nov 2009
- Posts
- 41
- Rep Power
- 0
Implementing a singly linked list
Hello,
I wanted to implement a singly linked list with following operations:
Add to end, remove from end, delete everything.
I've already created a ListNode class which's objects contain an element and another ListNode object.
The List class has one field called 'head', which is a ListNode object.
Now for the add method:
Now the else part is missing and I have no idea.Java Code:public void add(T t){ if(this.head == null){ this.head.setElement(t); }else{ } }
Can anyone help me?
- 04-11-2010, 09:39 PM #2
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
- 04-12-2010, 09:19 PM #3
Member
- Join Date
- Apr 2010
- Posts
- 13
- Rep Power
- 0
see the below code which is complete solution
class Node
{
int a;
Node n=null;
}
class SLL
{
public static void main(String s[]) throws Exception
{
Node head=new Node();
int i=0,cnt=0;
while(true)
{
System.out.println("\n your choice :");
System.out.println(" 1.add ");
System.out.println(" 2.remove ");
System.out.println(" 3.display ");
System.out.println(" 0.exit");
System.out.print("\n Value : ");
i=System.in.read();System.in.read();System.in.read ();
if(i==48)
break;
if(i==49)
SLL.add(head,++cnt);
if(i==50)
SLL.remove(head);
if(i==51)
SLL.display(head);
}
}
static void display(Node head)
{
Node temp=head;
System.out.print("\n\t SLL is : ");
if(head.n==null && head!=null)
{
System.out.println(head.a);
return;
}
while(temp.n!=null)
{
System.out.print(temp.a+"->");
temp=temp.n;
}
System.out.print("\b\b. ");
}
static void remove(Node head)
{
Node temp=head;
Node t1;
while(temp.n!=null)
{
t1=temp.n;
if(t1.n==null)
{
temp.n=null;
break;
}
temp=t1;
}
if(head.n==null && head!=null)
{
System.out.println("\n\t No element in the list..");
System.exit(0);
}
display(head);
}
static void add(Node head,int cnt)
{
if(cnt==0)
head.a=cnt;
else
{
Node temp=head;
while(temp.n!=null)
{
temp=temp.n;
}
temp.n=new Node();
temp.a=cnt;
}
display(head);
}
}
try this code to run which is complete solution of your problem.
Similar Threads
-
Linked List help
By alpdog14 in forum New To JavaReplies: 3Last Post: 10-07-2009, 09:34 PM -
Trouble Developing Singly Linked Circular List
By VinceGuad in forum New To JavaReplies: 14Last Post: 02-25-2009, 04:38 PM -
Linked list
By rosh72851 in forum New To JavaReplies: 1Last Post: 02-05-2009, 07:21 AM -
Linked List integer list
By igniteflow in forum Advanced JavaReplies: 1Last Post: 12-10-2008, 08:53 PM -
Help with linked list
By trill in forum New To JavaReplies: 1Last Post: 08-07-2007, 07:29 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks