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 ... )

Similar Messages

  • Add or remove elements from a list attached to session duplicated the size

    Hi All,
    I have a jsp page that in there I'd like to show three columns in a table:
         <c:forEach var="thesaurus" items="${sessionScope.collection.thesaurusList}">
           <tr>
                        <td class="check"><input type="checkbox" name="word" value="${thesaurus.key}" ></td>
                        <td><c:out value="${thesaurus.key}"></c:out></td>
                        <td>${ts:getThesuaursRelationDescription(thesaurus.relation)}</td>
                        <td>${ts:getThesaurusSynonymsDescription(thesaurus.synonymsList)}</td>
              </tr>
           </c:forEach>thesuaurList is an ArrayList that holds object of type Thesaurus class ( a simple java bean). collection object is attached to session via a servlet.
    ts are tag that i have defined in my tag library.getThesuaursRelationDescription and getThesaurusSynonymsDescription are two static method and there's no problem with any of these classes.
    It all works ok but when I refresh the page, the list size gets duplicated each time and i can't see why? why items are added again to my list? Is that because i have collection object as an session attribute?
    If i replace the above code with jsp scriptlet it works fine:
    <%
                    Collection collection = (Collection) session.getAttribute("collection");
                    List< Thesaurus> thesauruses= collection.getThesaursList();
                    int i = 0;
                    for (Thesaurus thesaurus: thesauruses)
                    %>
                     <tr>
                        <td class="check"><input type="checkbox" name="word" value=<%=thesaurus.getKey()  %> ></td>
                        <td><%=thesaurus.getKey()%></td>
                        <td><%=ThesaurusUtil.getThesuaursRelationDescription(thesaurus.getRelation())%></td>
                        <td><%=ThesaurusUtil.getThesaurusSynonymsDescription(thesaurus.getSynonymsList())%></td>
                    </tr>
                    <%
                    %>Thanks in advance.

    Gr8 not a problem why do you use a composite view pattern.
    --->In that case make use of Proper patterns in your design before forwading it to a view.
    ---->Use a Public JSP Statically include JSP's in WEB-INF folder using static page include which happens at compile time.
    REGARDS,
    RaHuL

  • Removing specific element from a list

    Hello, I'm very new to java, and to programming in general.
    I'm trying to write a secret santa app for my family for christmas. Essentially the idea is that 7 names are put into a list, and each time a name is "pulled" (i.e. randomly assigned to a name /= itself) it will be removed from the list of available names to assign.
    String[] nList = { name2, name3, name4, name5, name6, name7 }; // store names for random use
    Random r = new Random();
    name1assign = nList[r.nextInt(nList.length)];
    String[] nList2 = { name1, name3, name4, name5, name6, name7 };
    name2assign = nList2[r.nextInt(nList2.length)];
    My goal for this is to take the string that is equal to name1assign, and remove an element with that string from nList2.
    Can anyone give me some advice in this matter?
    Thanks.

    Sometimes a null value is used to indicate an 'empty' array element, but it would be better to try collections instead.
    You could use an ArrayList instead of an array. This has methods to remove items by index or value.
    An ArrayList also works with Collections.shuffle, which allows you to simply iterate over the list and not deal with random or removing elements at all.

  • Is it possible to rearrange the elements in a List after removing indexes?

    Hello,
    I am hoping someone can help me out w/a question.
    I have a list
    List<String>  Labels = new ArrayList<String> ();and I add 3 elements in the list
    labels.add("one"); //index 0
    labels.add("two"); //index 1
    labels.add("three");  //index 2Later on in the program I remove 2 indexes,
    labels.remove(0);
    labels.remove(2);When i try to iterate through labels it throws
    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1I perfectly understand the error. My question is this: after removing the indexes, how can i rearrange the list so that the one element that is left (currently at index 1) is set at index 0 so that it doesn't throw an exception ? is this doable ?
    Thanks very much for your help!!

    va97 wrote:
    Hello,
    I am hoping someone can help me out w/a question.
    I have a list
    List<String>  Labels = new ArrayList<String> ();and I add 3 elements in the list
    labels.add("one"); //index 0
    labels.add("two"); //index 1
    labels.add("three");  //index 2Later on in the program I remove 2 indexes,
    labels.remove(0);
    labels.remove(2);
    This doesn't work!
    Before those call the List looks like this:
    [one, two, three].
    After you call remove(0), it will look like this:
    [two, three]
    Now, when you try to call remove(2), it will throw an IndexOutOfBoundsException, as there is nothing at index 2 anymore.
    I perfectly understand the error. My question is this: after removing the indexes, how can i rearrange the list so that the one element that is left (currently at index 1) is set at index 0 so that it doesn't throw an exception ? is this doable ?I'm afraid you don't understand the error message correctly, since then your question would be different.
    The error message says "you tried to access something at index 1, but this list only is of size 1". This means that the only valid index at that moment is 0.

  • Impact of selecting "Removing Query from Selection List" in 2 channels.

    HI All ,
    I have customized a query in one channel (My Agreements and Contract Documents query in Master Agreements List channel) and have removed the standard query from the channel by checking the  "Remove Query from Selection List" and introduced my custom query in that query group .
    But  it resulted in break in chain for  "Master Agreements" link in "Contracts To Do List" channel as the link was pointing to standard  "My Agreements and Contract Documents" query and is displaying "The query can not be executed. Contact your system administrator" when ever I click on that.
    Any pointers on how to overcome above scenario wud be gr8!
    Regards,
    Uday

    Hi Uday,
    In order for To Do List channel to work, the query definition should be in the Master Agreement List query group. Do you still want the standard query in the To Do List? If so, you would have to leave it on the Query Group as To Do list is pointing to it. May be change the display name of the query so you can differentiate between the 2 queries. The other option is change the To Do channel to point to the custom query.
    Regards,
    Vikram

  • How to add new data element to field list

    Hi,
    I am implementing Succession Planning 3.0 SP1.
    To make new data element was successful.
    I want to use them as sort field, however I don't know how to add them to the list of fields with caption.
    (i.e. to setting Visualize>My Org Units>Sort Fields)
    If you know how to config data elements usw. Please advise.
    Best Regards,
    Hiroshi Takimoto

    Hi Hiroshi,
    There are 2 ways to do this, both involving some customization of the application.
    1) Extend your HR-OCI views (TMC_O_SUCC_T & TMC_O_SUCC_B for My Org Units and TMC_IN_REP_T_DT & TMC_IN_REP_B_DT) to include Short Name. You probalby want to seek help from an OM consultant if this is not your area of expertise.
    2) Create a linked data element that links together the existing data elements and a new data element which includes Short Name. Your new data element must have the name of the existing data elements or you should change the hierarchy configuration that uses these data elements. Beware that this can prove troublesome for the Position Hierarchy because of the "virtual root" that is created - sometimes the join does not work because of this.
    Best regards,
    Luke

  • Remove recently added play list?

    I need to try and claw back some space on my 160 classic. Is it possible to remove the recently played list? I never use it, nor do i really use the recently added list either. The only ones i use are top 25 and top rated. Would removing either of this lists give me back any space?

    Removing playlists won't free up storage space on your iPod. Playlists don't contain actual songs, just links to songs.
    If you want to free up space, you need to delete the song files themselves.

  • Invalid element 'welcome-file-list' in content of 'web-app',

    HI, folks.
    I recently used struts to develop a simple web applicaiton, and whenever I tried to use tag libs
    such as /WEB-INF/struts-html.tld
    /WEB-INF/struts-html.tld and
    tried to compile it, it gives out compile error such as:
    Error(52,21): Invalid element 'welcome-file-list' in content of 'web-app', expected elements '[taglib, resource-env-ref, resource-ref, security-constraint, login-config, security-role, env-entry, ejb-ref, ejb-local-ref]'.
    if I remove the above tag libs, the jsp file compiles
    without any problem.
    Are you guys familiar with these problems?
    please let me know if I'm doing anything foolish.
    Thanks!

    Unless some other elements tag are not close correctly this error does not make sense. Can you cut and paste your web.xml?
    It should look something like:
    <?xml version = '1.0' encoding = 'windows-1252'?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <welcome-file-list>
      <welcome-file>/untitled1.jsp</welcome-file>
    </welcome-file-list>
    <taglib>
      <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
      <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
    </taglib>
    </web-app>Charles.

  • Element in two lists

    Hey,
    I got a class for a tabbing page that is stored in an ArrayList A. This list A
    contains various pages for a JTabbedPane. Only some of those pages will
    also be stored in another ArrayList B. Hence list B will be smaller than A.
    When I remove such a tabbing page in list A, I'll check also a certain
    boolean if it is contained in list B, too.
    How can I get the index now in list B in an elegant way? First I gave all of
    those tabbing page classes an index variable for B, that I could check. My
    problem was, it seems to be a bit clumsy and I need to update that variable
    after each action (add/remove). Now I thought about in case I'd like to
    remove a page, to run thru the list B and compare the elements in that list
    directly with the one which is to be removed or compare just hashCode's of
    these elements with the one to be removed, in case it would work?!
    Which solution solves my problem best? - the first using an additional variable, comparing the elements or comparing just the hashCodes with the one element to be removed? TIA

    don't know the 'best' way, but if the elements of B are added from A,
    this might be all you need to do.
        Object o = listA.get(2);//<--2 is any number
        for(int x = 0,y = listB.size(); x < y; x++)
          if(listB.get(x).equals(o))
            listB.remove(x);
        }

  • I have iPhone 4s, and using latest iOS. When I try to open any link from Twitter or Facebook, it goes to open some wrong webpage. My iphone seems to be infected or suffering from some spyware or malware. How can I remove this wrong link opening

    I have iPhone 4s, and using latest iOS. When I try to open any link from Twitter or Facebook, it goes to open some wrong webpage. My iphone seems to be infected or suffering from some spyware or malware. How can I remove this wrong link opening ? Please help me to resolve...

    I think the McAfee suite will do the trick when I pay them a one-time fee of $69 or $179 for a year for unlimited support.
    Your call of course but IMO a waste of money. Please read this first:
    There are many forms of ‘Malware’ that can affect a computer system, of which ‘a virus’ is but one type, ‘trojans’ another. Using the strict definition of a computer virus, no viruses that can attack OS X have so far been detected 'in the wild', i.e. in anything other than laboratory conditions. The same is not true of other forms of malware, such as Trojans. Whilst it is a fairly safe bet that your Mac has NOT been infected by a virus, it may have another security-related problem, but more likely a technical problem unrelated to any malware threat.
    You may find this User Tip on Viruses, Trojan Detection and Removal, as well as general Internet Security and Privacy, useful:
    https://discussions.apple.com/docs/DOC-2435
    The User Tip (which you are welcome to print out and retain for future reference) seeks to offer guidance on the main security threats and how to avoid them.
    More useful information can also be found here:
    http://www.reedcorner.net/mmg/

  • How Can I Remove All the Links in a Document?

    I want to remove all the internal and external bound links in
    a number of my html documents. Is there any way I can do this with
    one action. I tried using Control + F on </a> and replacing
    it with nothing and that works. But Control + F on <a
    href="URL"> doesn't work as the url for that is different every
    time.
    Is it possible to remove all the links in one sweep, I hate
    to do it manually one by one as there are just so many?

    Tanim23 wrote:
    > Is it possible to remove all the links in one sweep
    Yes. In the Find and Replace dialog box, set Search to
    Specific Tag, and
    select a in the drop-down menu alongside. Then set Action to
    Strip Tag.
    You can do this in the current document, a particular folder,
    or the
    entire site, depending on what you select in the Find in
    drop-down menu.
    David Powers, Adobe Community Expert
    Author, "The Essential Guide to Dreamweaver CS4",
    "PHP Solutions" & "PHP Object-Oriented Solutions"
    http://foundationphp.com/

  • How Can I Remove the Home Link on the Main Page

    I am using PT 8.49 and I am creating a custom page where the only options I'd like to show on the page are my custom menu option and "Sign out" at the top right. I'd like to remove the "Home" link on the top right menu because I am doing the selection for them. I don't want them to be able to go back to the Home menu once they've entered my custom page. I have everything working the way I'd like except that I cannot get rid of the "Home" link. Can anyone help with that?
    I am also using a template in portal called HOMEPAGE_DESIGNER_TEMPLATE as this causes the page to display without the left menu, as I want it to be.
    Thanks for your help!

    Restore the default home page
    * https://support.mozilla.com/en-US/kb/How%20to%20set%20the%20home%20page#w_restore-the-default-home-page
    Now, set a single web site as your home page
    * https://support.mozilla.com/en-US/kb/How%20to%20set%20the%20home%20page#w_set-a-single-web-site-as-your-home-page
    Check and tell if its working.

  • How do I remove the shared link that's shares my contact information? I need to remove the link off all my contacts and not just on an individual basis. Somehow my boyfriends iPhone can see all of my contact information.

    Unshare my contact information so no one is able to see it.

    In addition my icloud is turned off and I also removed the shared linked off of my boyfriend's contact information on my phone but he still has access to all my contact information. I see the shared links in all my other contacts as well but I'm not sure if unlinking each contact will help. Is there another way to unshare the contact information?

  • How to remove the "text link" of an action link

    Hi everyone,
    after searching the forum and web with no luck, I need help on this topic. I'm working with many reports which link to others dashboards. These dashboards were created in OBIEE 10 and migrated to 11.1.1.3.
    What we wanted to do (and achieved in 10g) was to be able to click on some data (on a value of a graph, a value/column header in a table) and navigate to another dashboard. OBIEE 11g does this from the Criteria tab --> Column properties --> Interaction and selecting Action Links.
    In 11g, when doing this Action Links and clicking on a value, appears a "text link" ( screenshot : [https://picasaweb.google.com/102130000310148493868/Screenshots#5646178057282726354] ), so the user would need to do 2 clicks (one on the value and other in the text link).
    Is there any way to remove this Text Link? It can be a bit annoying if there is always one option, and needless.
    Thank you

    Hi Elena!
    In teh Interaction Tab (in the Column Properties window), once you create the action,you will right there a check box that says: "Do not display in a popup if only one action link is available at runtime". Clik on the check box, and you are ready to go!
    Please assign points if helful.
    J.-

  • Help needed in removing duplicate items of list box  in java

    How to remove duplicate items of list box while dynamically inserting (on-click event)
    It is not identifying duplicate data
    Variable name is HP_G1
    HP_dmg1 = (DefaultListModel) HP_G1.getModel();
    int a = HP_G1.getModel().getSize();
    System.out.println("HP list no--------> "+a);
    if(a!=0)
    for (int j=0; j<a; j++)
    String item1 = String.valueOf(HP_List.getModel().getElementAt(j));
    System.out.println("HP list added--------> "+item1);
    if(HP_dmg1.equals(item1)){
    HP_dmg1.remove(j);
    else
    HP_dmg1.addElement(GPL);
    }

    Your code is unreadable, so I'll ignore it. In the future please press the message editor's CODE button to format code.
    As to your problem, to the point you normally use a Set instead of List when you don't want duplicates in a collection.

Maybe you are looking for