CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2015
    Posts
    1

    How to create a single-linked list

    I suppose this post belongs to this forum and not to Java.
    I am new to data structures and I have the following Java class:

    Code:
    public final class Node<T>
    {
    	public final T v; 
    	public Node<T> next;
    	
    	public Node (T val, Node<T> link) {v = val; next = link}
    }
    How do I manually create a single-linked list of 5 integers?

    I will be implementing Iterator<T> and Iterable<T> interfaces in order to use a "foreach" loop, that is why I need to know how to create a list of type Node<T>.

    Respectfully,
    Jorge Maldonado

  2. #2
    Join Date
    Jun 2015
    Posts
    208

    Re: How to create a single-linked list

    Quote Originally Posted by JORGEMAL View Post
    How do I manually create a single-linked list of 5 integers?
    Why don't you just create five nodes and chain them up like,

    Code:
    Node<Integer> list = null; // empty list
    list = new Node<Integer>(5,list); // add last node
    list = new Node<Integer>(4,list);
    list = new Node<Integer>(3,list);
    list = new Node<Integer>(2,list);
    list = new Node<Integer>(1,list); // add first node
    The list variable now holds a list of 5 nodes with values 1 thru 5.

    It can easily be turned into a loop if you prefer that.

    What's missing is the actual SingleList class that holds the list variable. SingleList will define list operations and implement the Iterable interface. The Node class will be an implementation detail.
    Last edited by tiliavirga; November 17th, 2015 at 10:48 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured