Implementing my own linked lists...aiiieee!

Hi,
I'm trying to implement my own linked list structure oftype String. It will eventually go to form a simple text editor, with each line of a file being loaded into its own String node.
However, im having problems implementing the list itself :)
So far ive got the file to read in succesfully, but now im stuck...how do i load up a line into a new node? and what about the head/tail nodes, they just confuse me! Do i have to write a seperate 'List' class and create an object of that, much like the LinkedList class with Java?
Any help or a nudge in the right direction would be appreciated,
TIA
andrew
PS code below ...
=================================
=================================
import java.io.*;
import java.util.*;
class Editor {
public static void main(String[] args) {
///LOAD UP THE TEXT FILE//////////////////////////////////////
     String file = "s.txt";
     String line;
     System.out.println(System.in);
     //testing here...
StringNode alist = new StringNode(null,null);
     try{
          FileReader FR = new FileReader(file);
          BufferedReader BR = new BufferedReader(FR);
          while ( (line = BR.readLine()) != null ){
               alist.addNodeAfter(line);
               System.out.println(line);
               }//while
     }//try
     catch(IOException e){
          System.out.println(file + " not found");
     }//catch
///COMMANDS///////////////////////////////////////////////////
//text editor commands to be input via command line type console. how to grab inputs on return?
}//main
}//Editor
//code to create a node...but now what?
     class StringNode
     private String data;
     private StringNode link;
     // constructor for initialisation
     public StringNode(String initialData, StringNode initialLink)
          data = initialData;
          link = initialLink;
     // accessor method to get the data from this node
     public String getData( )
          return data;
     // accessor method to get a reference to the next node after this node.
     public StringNode getLink( )
          return link;
     // modification method to set the data in this node.
     public void setData(String newData)
          data = newData;
     // modification method to set the link to the next node after this node
     public void setLink(StringNode newLink)
          link = newLink;
     // add a new node after this node
     public void addNodeAfter(String item)
          link = new StringNode(item, link);
     // modification method to remove the node after this node.
     public void removeNodeAfter( )
          link = link.link;
     // compute the number of nodes in a linked list
     public static int listLength(StringNode head)
          StringNode cursor;
          int answer;
          answer = 0;
          for (cursor = head; cursor != null; cursor = cursor.link)
               answer++;
          return answer;
     // print the nodes in a linked list
     public static void listPrint(StringNode head)
          StringNode cursor;
          for (cursor = head; cursor != null; cursor = cursor.link)
               System.out.println(cursor.getData());
     // print the nodes in a linked list skipping dummy node at head
     public static void listPrint2(StringNode head)
          StringNode cursor;
          for (cursor = head.link; cursor != null; cursor = cursor.link)
               System.out.println(cursor.getData()+" ");
     // search for a particular piece of data in a linked list
     public static StringNode listSearch(StringNode head, String target)
          StringNode cursor;
          for (cursor = head; cursor != null; cursor = cursor.link)
               if (target == cursor.data)
                    return cursor;
          return null;
}

You wouldn't by any chance be doing computer science at Cardiff university would you and have been given this as an assignment?

Similar Messages

  • Implementing TRIE using linked lists

    Node InsertNode(string name, Node root)
    int index = 1;
    string key;
    Node currentNode = root;
    while (index <= name.Length)
    key = name[index - 1].ToString();
    Node resultNode = currentNode.Children.GetNodeByKey(key);
    if (resultNode == null)
    Node newNode = new Node(key, name.Substring(0, index));
    if (index == name.Length)
    newNode.IsTerminal = true;
    currentNode.Children.Add(newNode);
    currentNode = newNode;
    else
    currentNode = resultNode;
    index++;
    return root;
    i want to use linked lists. i dont no what nodes are.like basically how do i use linked lists in the place of nodes in this code?
    thanx

    http://www.codeproject.com/KB/recipes/PhoneDirectory.aspx?display=Print <= code tags?
    coherent questions?
    class LinkedListNode {
    private LinkedListNode next;
    private Object data;
    public void insertAfter(Object data) {
    LinkedListNode newNode = new LinkedListNode();
    newNode.data = data;
    newNode.next = next;
    this.next = newNode;
    this is ur typical insert method for a linkedlistnode. you're saying nodes do the dirty work. how do connect this code with the one i posted in my previous msg? where do i get NODE from. What is this class.

  • Help on resetting my own linked list.

    I got a Binary tree project, but to get things started, i decided to put all the elements into a LinkedList first.
    Anyway, it seems i forgot how to go back to the root of my linkedList. I can traverse through the LinkedList, but it seems that whenever I try to call it again, it's already at the end of the List. My linkedList consist of a Integer, and a the next Node is called "left" atm.
    Here's my code:
    class MyTree { //class definition
         class Node {
              int data;
              Node left;
              Node right;
    private Node root;
    private int [] rdata;
    Node m = new Node();
    BufferedReader in;
       public void generate(int n, int range){
              Random r = new Random();
              rdata  = new int[n];
                      for (int i = 0; i<n; i++) {
                            rdata[i] = r.nextInt(range);
              Node b = new Node();
              for (int j = 0; j<n; j++){ 
                   b.data = rdata[j];
                   m.left = b;
                   m = m.left;
                   System.out.println("m.data " + m.data);
                   Now whenever I try to call it back again, It would only print the last integer in the LinkedList, so I had to use an array to set it up it again basically.
         public void show() {
                   Node b = new Node();
                   for (int j = 0; j<rdata.length; j++){ 
                   b.data = rdata[j];
                   m.left = b;
                   m = m.left;
                   System.out.println("m.data " + m.data);
         }I'll like to traverse through the list again without setting up the linked list every time.
    Thanks in Advance.
    Message was edited by:
    Vertix
    Message was edited by:
    Vertix
    Message was edited by:
    Vertix
    Message was edited by:
    Vertix
    Message was edited by:
    Vertix

    Well, I tried to remove Node b, and just use the Node
    m to set up my LinkedList.[ code snipped ]
    But it's giving NullPointerExceptions everytime I try to run it. I already
    created a Node m at the begging, so I don't see where it's getting the
    nullpointer.That's not how you should create that list. You need a new node per
    element in the rdata[] array. There are two possible states:
    1) there isn't a list yet, i.e. the 'root' element equals null
    2) there's a list already and 'm' points to the last element of the list.
    This is how you do it:m= root; // both are null; see 1)
    for (int i= 0; i < rdata.length; i++) { // build the list
       Node b= new Node(); // build a new node
       b.data= rdata;
    if (root == null) // first list element?
    root= b;
    else // no, hookup to last element
    m.left= b;
    m= b; // m points to last element
    kind regards,
    Jos

  • Help Implementing a queue as a circular linked list...

    I have a set of code that I need to implement a circular linked list into, but I am not sure how to approach it at all. If anyone can point me to some pseudo code or sample code that I can modify for my use, that would be great.
    I created a Class CircularQueue, which implements Queue, I just need to figure out how to write it.
    Heres the code I have:
    Queue Interface
    public interface Queue<ElementType> {
         public void enqueue(ElementType e);
         public ElementType dequeue();
         public ElementType front();
         public boolean isEmpty();
    Data Holder
    public class DataHolder<ElementType> {
         // instance variables
         private ElementType _data;
          * Constructor for objects of class DataHolder
         public DataHolder() {
              _data = null;
         public void setContents(ElementType anItem) {
              _data = anItem;
         public ElementType getContents() {
             return _data;
    DeqeueButton
    import javax.swing.*;
    import java.awt.event.*;
    public class DequeueButton extends JButton {
        // instance variables
        private Queue<SmartRectangle> _queue;
        private QueuePanel _queuePanel;
         * Constructor for objects of class DequeueButton
        public DequeueButton(QueuePanel aQueuePanel) {
            super("Dequeue");
            _queuePanel = aQueuePanel;
            _queue = aQueuePanel.getQueue();
            this.addActionListener(new DequeueButtonListener());
        private class DequeueButtonListener implements ActionListener {
            private final int MOVE_LENGTH = 25;    // square size + 5
            public void actionPerformed(ActionEvent e) {
                _queue.dequeue();   // remove item from queue
                _queuePanel.repaint();
    EnqueueButton
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class EnqueueButton extends JButton {
        // instance variables
        private Queue<SmartRectangle> _queue;
        private QueuePanel _queuePanel;
         * Constructor for objects of class EnqueueButton
        public EnqueueButton(QueuePanel aQueuePanel) {
            super("Enqueue");
            _queuePanel = aQueuePanel;
            _queue = _queuePanel.getQueue();
            this.addActionListener(new EnqueueButtonListener());
        private class EnqueueButtonListener implements ActionListener {
            private int _nextX, _nextY;
            private final int SQUARE_SIZE = 20;
            private final int MAX_X = 550;
            private final int MAX_Y = 350;
            private Color _currentColor;
            public EnqueueButtonListener() {
                _currentColor = Color.BLUE;
                _nextX = MAX_X;
                _nextY = MAX_Y;
            public void actionPerformed(ActionEvent e) {
                _queue.enqueue(new SmartRectangle(_nextX, _nextY, SQUARE_SIZE, SQUARE_SIZE, _currentColor, _queuePanel));
                this.changeColor();
                _nextX -= (SQUARE_SIZE+5);  // location of next square in line
                if (_nextX < 0)     // if we reach edge of window, wrap
                {   _nextY -= (SQUARE_SIZE+5);
                    _nextX = MAX_X;
                if (_nextY < 0)     // start over
                    _nextY = MAX_Y;
                _queuePanel.repaint();
            public void changeColor() {
                if (_currentColor == Color.BLUE)          
                    _currentColor = Color.RED;
                else if (_currentColor == Color.RED)      
                    _currentColor = Color.GREEN;
                else if (_currentColor == Color.GREEN)    
                    _currentColor = Color.YELLOW;
                else if (_currentColor == Color.YELLOW)   
                    _currentColor = Color.BLACK;
                else if (_currentColor == Color.BLACK)    
                    _currentColor = Color.BLUE;
    FrontButton
    import javax.swing.*;
    import java.awt.event.*;
    public class FrontButton extends JButton {
        // instance variables
        private Queue<SmartRectangle> _queue;
        private QueuePanel _queuePanel;
         * Constructor for objects of class DequeueButton
        public FrontButton(QueuePanel aQueuePanel) {
            super("Front");
            _queuePanel = aQueuePanel;
            _queue = aQueuePanel.getQueue();
            this.addActionListener(new FrontButtonListener());
        private class FrontButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                SmartRectangle rectangle = _queue.front();    // remove item from queue
                SmartRectangle displayRect = _queuePanel.getDisplayFrontRect();
                if (rectangle != null)
                    displayRect.setColor(rectangle.getColor());
                _queuePanel.repaint();
    QueueApp
    import javax.swing.*;
    import java.awt.*;
    public class QueueApp extends JFrame
         * Constructor for objects of class QueueApp
        public QueueApp(String title)
            super(title);
            this.setSize(600,450);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            QueuePanel queuePanel = new QueuePanel();
            javax.swing.JPanel buttonPanel = new JPanel(new FlowLayout());
            buttonPanel.add(new EnqueueButton(queuePanel));
            buttonPanel.add(new DequeueButton(queuePanel));
            buttonPanel.add(new FrontButton(queuePanel));
            this.add(queuePanel, BorderLayout.CENTER);
            this.add(buttonPanel, BorderLayout.SOUTH);
            this.setVisible(true);     
        public static void main (String [] args)
            QueueApp app = new QueueApp("Queues at work: Object Oriented implementation.");
    QueuePanel
    import javax.swing.*;
    import java.awt.*;
    public class QueuePanel extends javax.swing.JPanel {
        // instance variables
        private Queue<SmartRectangle> _queue;
        private SmartRectangle _frontRect;
         * Constructor for objects of class QueuePanel
        public QueuePanel() {
            super();
            _queue = new CircularQueue<SmartRectangle>();
            _frontRect = new SmartRectangle(50,50,20,20,Color.WHITE, this);
       public Queue<SmartRectangle> getQueue() {
           return _queue;
       public SmartRectangle getDisplayFrontRect() {
           return _frontRect;
       public void paintComponent(Graphics aBrush) {
           super.paintComponent(aBrush);
           Graphics2D aBetterBrush = (Graphics2D) aBrush;
           Queue<SmartRectangle> tempQueue = new CircularQueue<SmartRectangle>();
           if (_frontRect.getColor() != this.getBackground())
               _frontRect.fill(aBetterBrush);
           while (!_queue.isEmpty()) {       // remove and display contents
               SmartRectangle rectangle = _queue.dequeue();
               rectangle.fill(aBetterBrush);
               tempQueue.enqueue(rectangle);
           while (!tempQueue.isEmpty()) {    // put contents back into _queue
               _queue.enqueue(tempQueue.dequeue());
           _frontRect.setColor(this.getBackground());
    SmartNode
    public abstract class SmartNode<ElementType> {
         public abstract boolean isEmpty();
         public abstract SmartNode<ElementType> dequeue(DataHolder<ElementType> aHolder);
         public abstract void front(DataHolder<ElementType> aHolder);
         public void enqueue(ElementType anItem){}
         public void setNext(SmartNode<ElementType> aNode) {
         }  // override as needed
         public void setPrev(SmartNode<ElementType> aNode) {
         }  // override as needed
    SmartRectangle
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    public class SmartRectangle extends Rectangle2D.Double {
        // instance variables
        private JPanel _panel;
        private Color _color;
         * Constructor for objects of class SmartRectangle
        public SmartRectangle(int x, int y, int aWidth, int aHeight, Color aColor,
                              JPanel aPanel) {
            super(x, y, aWidth, aHeight);
            _panel = aPanel;
            _color = aColor;
        public void setLocation (int x, int y) {
            this.setFrame(x, y, this.getWidth(), this.getHeight());
        public Color getColor() {
            return _color;
        public void setColor(Color aColor) {
            _color = aColor;
        public void fill(Graphics2D aPaintBrush) {
            Color savedColor = aPaintBrush.getColor();
            aPaintBrush.setColor(_color);
            aPaintBrush.fill(this);
            aPaintBrush.setColor(savedColor);
    }

    > Yea I think I understand the concept of it, but I
    dont know what the code is supposed to look like.
    Showing you what the code is supposed to look like would be effectively giving you the answer, which kind of defeats the purpose of "extra credit". Have you tried anything so far? Post what you've got, and we can give you hints on how to work through it. I thought some of the descriptions here were very explicit hints, but if you need some additional guidance, let us know your specific questions (other than "show me the code").
    Good luck!
    ~

  • Sorting My Linked List

    Alright, here's the problem. I have my linked list, either imported from a text file or inputted by the user. Now, I need to sort it by the date and the time strings... Yet, every time I do I get an NullPointException. Can anyone help? Here's my code for the list:
    public class ListReferenceBased implements ListInterface{
         //references to the linked list items
         private Node head;
         private int numItems; //number of items that exist in list
         //Default Constructor
         //sets both items to null
         public ListReferenceBased(){
              numItems = 0;
              head = null;
         //if the numItems in the list is empty
         //returns true.
         public boolean isEmpty(){     
              return numItems == 0;
         // returns numItems, aka the size of the list
         public int size(){
              return numItems;
         //finds a node by setting a node to the 'head'
         // and loops through to the index 'resetting'
         // curr to the 'next' node.
         private Node find(int index){
              Node curr = head;
              for( int skip = 1; skip < index; skip++){
                   curr = curr.getNext();
              return curr;
         public Object get(int index)
              throws ListIndexOutOfBoundsException{
              //catches if list does not reach the index given
              //loops through the index
              if(index >= 1 && index <= numItems){
              //sets curr to the index through find()
              Node curr = find(index);
              //sets dataitem to the current node
              Object dataItem = curr.getItem();
              return dataItem;
              }else{
              throw new ListIndexOutOfBoundsException("The List index is out of bounds on get");
         public void add(int index, Object item)
              throws ListIndexOutOfBoundsException{
              //checks to make sure there are no nodes yet
              //if there are inserts them in the list
              //by moving
              if(index >=1&& index<= numItems+1){
                   if(index==1){
                        // if no list exists
                        //creates a new node and sets it to head
                        Node newNode = new Node(item, head);
                        head = newNode;
                   }else{
                             //inserts the node at the index
                             //by finding it first
                             Node prev = find(index-1);
                   //creates a new node by placing the Object item
                   //and the 'new prev' node into a node
                   //'deleting' the old 'bonds'
                   Node newNode = new Node(item, prev.getNext());
                   rev.setNext(newNode);
                        //increments number of items in list
                        numItems++;
              }else{     
                        throw new ListIndexOutOfBoundsException("List index out of bounds");
         public void remove(int index)
              throws ListIndexOutOfBoundsException{
              //catches the list if it doesn't exist
              //checks to make sure list exists
              if(index>=1&& index<= numItems){
                   //if only the head exists
                   //calls next node else moves
                   //the node away and moves the prev
                   //on up.
                   if(index==1){
                        head = head.getNext();
                   }else{
                        Node prev = find(index-1);
                        Node curr = prev.getNext();
                        prev.setNext(curr.getNext());
                   //decreases the number of items in list
                   numItems--;
              }else{
         throw new ListIndexOutOfBoundsException("List index out of bounds");
         //sets the numItem to null telling the list it
         //does not exist
         public void removeAll(){
              head = null;
              numItems=0;
              

    Yeah, unfortunately, I had to design my own linked list for my assignment (that's taken almost 40+ hours). So, now every alogrithm I've tried to write seems to give me a null pointer, for example this one
    public void sort(){
              //loop through all existing nodes
              for(Node curr = head; curr != null; curr = curr.getNext()){
                   //parse the string of the current node
                   //to a string value
                   Node current = curr.getNext();
                   Node next = current.getNext();
                   Node temp;
                   String thisline = current.getItem().toString();
                   System.out.println(thisline);
                   StringTokenizer parser = new StringTokenizer ( thisline, "\t" );
                   String thisdate = parser.nextToken();
                   String thistime = parser.nextToken();
                   String thisline2 = next.getItem().toString();
                   System.out.println(thisline2);
                   StringTokenizer parser2 = new StringTokenizer ( thisline2, "\t" );
                   String thisdate2 = parser.nextToken();
                   String thistime2 = parser.nextToken();
                   //compares the dates of next in list
                   if(thisdate.compareTo(thisdate2)==1){
                        next.setNext(current);
                        current.setNext(next.getNext());
                        printList();
                        //if dates equal, compare the times
                   //if equal move to new position
                        //delete old position
    }Pretty much I believe moving the positions is causing the problems after the first run around. Any suggestions?

  • Remove element in linked list linked list

    here's my codes
    public class Student
        private String name, matric;
        public Student(){}
        public Student( String name, String matric)
           this.name = name;
           this.matric = matric;
         public String getName()
         { return name;}
         public void setName(String name)
         { this.name = name;}
         public String getMatric()
         { return matric;}
         public void setMatric( String matric)
         { this.matric = matric;}
         public String toString()
            return "Name: " + name + ", Matric no: " + matric + "\n";   
        }// end student classthe link list class
    public class LinkedList extends java.util.LinkedList
        // instance variables - replace the example below with your own
        private ListNode firstNode;
        private ListNode lastNode;
        private ListNode currNode;
        private String name;
         * Constructor for objects of class LinkedList
        public LinkedList(String s)
            name = s;
            firstNode = lastNode = currNode = null;
        public LinkedList() {this("list");}
        public synchronized void insertAtFront(Object insertItem) {
            if (isEmpty())
                firstNode = lastNode = new ListNode(insertItem);
            else
                firstNode = new ListNode(insertItem, firstNode);
        public synchronized void insertAtBack(Object insertItem) {
            if (isEmpty())
                firstNode = lastNode = new ListNode(insertItem);
            else
                lastNode = lastNode.next = new ListNode(insertItem);
        public synchronized Object removeFromFront() throws EmptyListException {
            Object removeItem = null;
            if (isEmpty())
                throw new EmptyListException(name);
                removeItem = firstNode.data;
                if (firstNode.equals(lastNode))
                    firstNode = lastNode = null;
                else
                    firstNode = firstNode.next;
                return removeItem;    
        public synchronized Object removeFromBack() throws EmptyListException {
            Object removeItem = null;
            if (isEmpty()) throw new EmptyListException(name);
            removeItem = lastNode.data;
            if (firstNode.equals(lastNode))
                firstNode = lastNode = null;
            else {
                ListNode current = firstNode;
                while (current.next != null)
                    current = current.next;
                lastNode = current;
                current.next = null;
            return removeItem;
        public synchronized boolean isEmpty()
        { return firstNode == null;}
        public synchronized Object getFirst() {
            if (isEmpty())
                return null;
               else {
                    currNode = firstNode;
                    return currNode.data;
        public synchronized Object getNext() {
            if (currNode != lastNode) {
                currNode = currNode.next;
                return currNode.data;
            else
                return null;
        public synchronized String print() {
            String out = "";
            if (isEmpty()) {
                out = "Empty "+ name;
            out = "The "+ name+ " is:\n";
            ListNode current = firstNode;
            while (current != null) {
                out += ""+ current.data.toString();
                current = current.next;
            return out;
        public synchronized Object getLast() {
            if (isEmpty())
                return null;
            else {
                currNode = lastNode;
                return currNode.data;
    }// end LinkedListand the application class
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class StudentAppLL
        public static void main(String[] args) throws IOException {
            LinkedList std = new LinkedList();
            BufferedReader br = new BufferedReader(new FileReader("studentIn.txt"));
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("studentOut.txt")));
            String line = br.readLine();
            while (line != null) {
                StringTokenizer tk = new StringTokenizer(line);
                while (tk.hasMoreTokens()) {
                    String n = tk.nextToken();
                    String m = tk.nextToken();
                    Student a = new Student(n, m);
                    std.insertAtFront(a);
                    line = br.readLine();
            std.print();
            System.out.print(std.getFirst());
            Student data = (Student)std.getFirst();
            String matric;
            String nm = "Zaki";
            while (data != null) {
                if (data.getName().equalsIgnoreCase(nm)) {
                    System.out.print(data.getName()+ " ada\n");
                    //std.re
                    data = (Student)std.getNext();  
            Student b = new Student("Umar","2004163943");
            std.insertAtBack(b);
            String name = "", matric = "", s = "";
            boolean stop = false;
            int size = std.size();
            JOptionPane.showMessageDialog(null, size);
            s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
                                           "\nV: View Sorted Student List\nS: Stop ");
            while(!stop){
                if (s.equalsIgnoreCase("A")){
                    name = JOptionPane.showInputDialog("Enter student name: ");
                    matric = JOptionPane.showInputDialog("Matric number: ");
                    Student student = new Student(name, matric);
                    std.insertAtBack(student);
                    s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
                                           "\nV: View Sorted Student List\nS: Stop ");
                else if (s.equalsIgnoreCase("R")){
                    Student data = (Student)std.getFirst();
                    Student first = (Student)std.getFirst();
                    Student last = (Student)std.getLast();
                    JOptionPane.showMessageDialog(null, "First: "+ first+ "\nLast: "+ last);
                    String ns = JOptionPane.showInputDialog("Enter the student's name");
                    while (data != null) {
                        // buang kalau pd bhgn dpn
                        if (data.getName().equalsIgnoreCase(ns) && ns.equalsIgnoreCase(first.getName())) {
                            JOptionPane.showMessageDialog(null, first.getName());
                            JOptionPane.showMessageDialog(null, data.getName()+ " kena buang");
                            //std.removeFromFront();
                            std.remove(data);
                            s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
                                           "\nV: View Sorted Student List\nS: Stop ");                                       
                         if (data.getName().equalsIgnoreCase(ns) && ns.equalsIgnoreCase(last.getName())) {
                            std.removeFromBack();
                            JOptionPane.showMessageDialog(null, data.getName()+ " kena buang");
                             s = JOptionPane.showInputDialog("A: Add Student\nR: Remove Student" +
                                           "\nV: View Sorted Student List\nS: Stop ");
                         data = (Student)std.getNext();  
                    }// habis while loop
                // keluar jika pilih 's'
                else if (s.equalsIgnoreCase("S")){ stop = true;}
                else { JOptionPane.showMessageDialog(null, "Wrong input"); }                    
            JOptionPane.showMessageDialog(null, std.print());
            br.close();
            pw.close();
        }// end main class
    }and here's the studentIn.txt data
    Ahmad 2004199877
    Hanif 2005378219
    Zaki 2004456790
    how can i do it? i mean to remove other than first element?
    Message was edited by:
    ikki_72

    > public class LinkedList extends java.util.LinkedList
    // instance variables - replace the example below with your own
    private ListNode firstNode;
    private ListNode lastNode;
    private ListNode currNode;
    private String name;
    [ ... ]Eeeeeeeeeew! Don't do that ever again! A java.util.LinkedList is very
    well capable of managing a linked list (it is a linked list after all).
    Either build your own linked list mechanics or use a LinkedList as
    one of the member variables of your class, but please don't do this.
    kind regards,
    Jos ( ... that was scary ... )

  • Linked lists in labview

    Hi
    I want to create a linked list in labview. How can i do that in labview?
    If its not possible how can i implement in labview?

    I'd say one of the best implementations of a linked list is an Array of DVR's, just like you can have an array of pointers in C, the next and previous is ofc the place in the array. The question if ofc what you're trying to achieve.
    A "pure linked list" require a Cluster with a Next and Previous-DVR (or the name of a queue, though i dont know how the system would handle having thousands of 1-element queues) and either a Self-DVR or the information.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • Linked Lists

    I am trying to create a linked list with an object called ClassID But I am confused on the constructor. Could someone point me in teh right direction. this is what i got:
    import java.io.*
    public class Link
         public ClassID id;
         public Link next;
    public Link(ClassID id)
         id = new ClassID(id);
         

    Sorry, after rereading your initial post a third time, I see there is more to what you are asking and displaying than is easily discernable.
    I am assuming you mant the linked list wis of type ClassId, if ClassId was actually meant to be the data objects stored in the list then you must give your Linked List a new name, so say ClassLl. If this is the case replace ClassId with ClassLl in my example below.
    First, when you are using a constructor you don't really want to pass in "id"s and you definitely don't need "next". This is because the purpose of the constructor is to build a new linked list, and id and next should never be used in making a new linked list. The ClassId object if you have to create your own linked list without using the collections libraries should have a id and next field, but they should not be necessary for the constructor. The id, next, and ClassId if it is meant to be the data stored all should only come into play in methods manipulating the linked list.
    At most, you may have an already cronstructed linked list that you plan to pass to the linked list, but there is never a reason to pass id or next to a constructor.
    so
    public class List
         public ClassID id = new ClassId(); //or = new LinkedList() if allowed
            public List()  //there is no preexisting linkedlist being passed in
         public List(ClassID inID)  //inId is a linkedlist
              id = inID;
    }In short, worry about setting up your linked list before you start trying to fill it with stuff.

  • Doubly Linked Lists

    Hi there,
    i have just started to use java and was on the topic of doubly linked list and am confused. Is it possible for someone to show me how to implement a doubly linked list????
    Thanx

    if i had to do it, then i'd make a class that's this linked list object, and another class that's node object.
    in list object i'd hold count of nodes (in case someone asks that, so i should not go through list and count all those 1000000 nodes), and would also have reference to first and last node.
    public class KstyleDLList {
    KstyleNode first = null;
    KstyleNode last = null;
    private int count;
    public int getCount() {
      return count;
    public void addNode(KstyleNode node) {
      last.setNext(node); // simply ignore returned value
                          // because if everything is OK, then value returned is null
      next = node;
    public void removeNode(int index) {
      // method body here
    public KstyleNode getFirst() {
      // method body here
    public Kstyle getLast() {
      // method body here
    class KstyleNode {
    private KstyleNode next = null;
    private KstyleNode prev = null;
    public KstyleNode setNext(KstyleNode next) {
      KstyleNode old = this.next;
      this.next = next;
      return old;
    public getNext() {
      // method body here
    public KstyleNode setPrev(KstyleNode prev) {
      // method body here
    public KstyleNode getPrev() {
      // method body here
    }and lots of other methods that i haven't implemented yet.. but this should give you some idea of what you're going to do...

  • Help abstract classes linked list

    I have a base abstract class Vegetable which is basically Node for a linkedlist
    The base class Vegetable has a few abstract methods Pumpkin, Carrot, Potato basically extends Vegetable
    Another class called VegetableCollection
    basically in VegetableCollection
    can this be done if the objects are different types eg Pumpkin, potato, Carrot?
    public void add(Vegetable addObject)
    head = new Vegetable(addObject);
    }

    I have a base abstract class Vegetable which is basically Node for a linkedlist
    The base class Vegetable has a few abstract methods Pumpkin, Carrot, PotatoYou probably wouldn't have abstract methods with those names. Abstract methods are methods that you will need to define in every subclass. And a subclass called Pumpkin probably won't have meaningful definitions for methods called Carrot and Potato.
    can this be done if the objects are different types eg Pumpkin, potato, Carrot?
    public void add(Vegetable addObject)
    head = new Vegetable(addObject);
    }Here is an example of "polymorphism" at work:
    import java.util.*;
    abstract class Vegetable
      public abstract void identify();
    class Carrot extends Vegetable
      public void identify()
        System.out.println("I'm a Carrot.");
    class Pumpkin extends Vegetable
      public void identify()
        System.out.println("I'm a Pumpkin.");
    public class Test
      public static void main(String args[])
        LinkedList<Vegetable> myVegetables = new LinkedList<Vegetable>();
        myVegetables.add(new Carrot());
        myVegetables.add(new Pumpkin());
        Iterator<Vegetable> i = myVegetables.iterator();
        Vegetable v = null;
        while(i.hasNext())
          v = i.next();
          v.identify();
    output:
    I'm a Carrot.
    I'm a Pumpkin.To get polymorphism to work, you need to:
    1) Define a base class with a method that you want in all the subclasses.
    2) Override the method in the subclasses so that it does what's necessary for that subclass.
    3) Store the subclass objects in a variable(or collection) whose type is the base class.
    4) Call the method on the base type variable. Then through the magic of polymorphism, java will examine the actual object stored in the base type variable to determine what subclass it is, and then java will call the version of the method in that subclass.
    As the previous poster mentioned, you need to define a class called Node, which has head, previous, and next members. Your Node class will also have a member variable called veggie, which will be of type Vegetable. Then you can assign a Carrot, Pumpkin, or Potato object to that member variable.
    I assume this is an exercise where you have to create your own linked list. Otherwise, you can use the linked lists provided by java, which are very easy to use.

  • How to implement a linked list in oracle ?

    HI All
    I want to know if there a way to implement a linked list in oracle ?
    Thanks in Advanced
    Naama

    A linked list is an array of the relevant data plus an indicator of the next and previous entries, right?
    Sounds easily achievable with any of the plsql collection types.
    The simplest would be a plsql associative array of a record
    Assignments of records in collections is always a bit hamfisted compared to sql objects types though (IMO).
    Something like ?
    DECLARE
    TYPE r_payload IS RECORD
    (col1 number,
      col2 number);
    TYPE r_array_entry is RECORD
    (prev_entry PLS_INTEGER,
      next_entry PLS_INTEGER,
      payload    r_payload);
    TYPE t_array IS TABLE OF r_array_entry INDEX BY PLS_INTEGER;
    v_array t_array;
    BEGIN
    NULL;
    END; 
      The use case for such a structure in properly coded SQL & PL/SQL is possibly the harder question.

  • How  to Implement a Chained Hash Table with Linked Lists

    I'm making a migration from C/C++ to Java, and my task is to implement a Chained Hash Table with a Linked List. My problem is to put the strings(in this case names) hashed by the table using de Division Metod (H(k)= k mod N) in to a Linked list that is handling the colisions. My table has an interface implemented(public boolean insert(), public boolean findItem(), public void remove()). Any Help is needed. Thanks for everyone in advance.

    OK. you have your hash table. What you want it to do is keep key/value pairs in linked lists, so that when there is a collision, you add the key/value pair to the linked list rather than searching for free space on the table.
    This means that whenever you add an item, you hash it out, check to see if there is already a linked list and if not, create one and put it in that slot. Then in either case you add the key/value pair to the linked list if the key is not already on the linked list. If it is there you have to decide whether your requirements are to give an error or allow duplicate keys or just keep or modify one or the other (old/new).
    When you are searching for a key, you hash it out once again and check to see if there is a linked list at that slot. If there is one, look for the key and if it's there, return it and if not, or if there was no linked list at that slot, return an error.
    You aren't clear on whether you can simply use the provided linked-list implementations in the Java Collections or whether you have to cobble the linked list yourself. In any case, it's up to you.
    Is this what you're asking?
    Doug

  • Implementation of Linked List class

    I am trying to implement the Linked List class for one week, but I couldn't figure it out. If you know, please let me know.

    Here is an example of a linked list. Hope that will help.
    // define a node of a linked list
    public class Node
    public int data; // point to data
    public Node next; // pointer to next node or point to null if end of list
    // listTest1
    public class ListTest1
    public static void main(String[] args)
    Node list;
    list = new Node();
    list.data = 3;
    list.next = new Node();
    list.next.data = 7;
    list.next.next = new Node();
    list.next.next.data = 12;
    list.next.next.next = null;
    Node current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();
    // other listnode
    public class ListNode
    public int data;
    public ListNode next;
    public ListNode()
    // post: constructs a node with data 0 and null link
    this(0, null);
    public ListNode(int value)
    // post: constructs a node with given data and null link
    this(value, null);
    public ListNode(int value, ListNode link)
    // post: constructs a node with given data and given link
    data = value;
    next = link;
    Contents of ListTest2.java
    public class ListTest2
    public static void main(String[] args)
    ListNode list = new ListNode(3, new ListNode(7, new ListNode(12)));
    ListNode current = list;
    while (current != null) {
    System.out.print(current.data + " ");
    current = current.next;
    System.out.println();

  • Implementing Double Linked Lists

    I have been set a task creating a java class to implement the data cells of a double linked list, then improving on this class so that it will implemt the interface of a LinearList using a double linked list.
    HELP?!?!?!?!

    i have implemented a small method.u can implement the remaining methods as u want. I have not tested the code. Just for idea i am giving it. try it.
    public class Node{
         Node leftNode;
         Node rightNode;
         int data;
         public Node addNode(Node node,int data,int position){
              Node originalCopy=node;
              for(int i=0;i<position;i++){
                   Node tempNode=new Node();
                   tempNode.data=data;
                   tempNode.leftNode=node;
                   tempNode.rightNode=node.rightNode;
                   node=node.rightNode;
              return originalCopy;
    This class represents a Doubly linked list and it provides operations on it.

  • Is it possible to implement or represent a Linked List in LabVIEW?

    Linked lists are a useful way to store and retrieve data and I am wondering if it is possible to create or acheive the same objective of a linked list in LabVIEW.

    A linked list is a collection of nodes, each node has data and a link (or pointer) to the location of the next node.
    In LabVIEW we can create a collection of nodes as an array of clusters. One element of the cluster will be our data, and the other will be an integer pointer to the location in the array, of our next node.
    In, fact you can go crazy and represent a LabVIEW Hierarchy in a similar fasion (a tree structure). Now, each cluster will have data about the VI (its Name, attributes, etc), an array of integers that point the the locations of calling VIs, and an array of integers that point the the locations of subVIs.
    You will, of course also need some tools for sorting your lists/trees and performing useful operations... lot's of fun!
    Good luck
    Jim

Maybe you are looking for