简体   繁体   English

如何从java中的链表中删除对象?

[英]how to remove a object from linked list in java?

i have one problem with my code ,i did a sample program to display the emp details from a linked list,now the problem when i trying to delete a particular entry means it doesn't work,i hope i did some mistake in my code could you suggest how to do that? 我的代码有一个问题,我做了一个示例程序来显示链接列表中的emp详细信息,现在我尝试删除特定条目时的问题意味着它不起作用,我希望我的代码中有一些错误你能建议怎么做吗?

import java.util.*;

class EmpDedup {
    int record;
    String fprint;
    int fid;

    EmpDedup(int record, String fprint, int fid) {
        this.record = record;
        this.fprint = fprint;
        this.fid = fid;
    }

    public int getRecord() {
        return record;
    }

    public String getFprint() {
        return fprint;
    }

    public int getFid() {
        return fid;
    }

    public static void main(String[] args) {
        int count = 0;
        LinkedList<EmpDedup> list = new LinkedList<EmpDedup>();
        list.add(new EmpDedup(101, "entry1", 20));
        list.add(new EmpDedup(102, "entry2", 30));
        list.add(new EmpDedup(103, "entry3", 40));
        list.add(new EmpDedup(104, "entry4", 50));

        Scanner input = new Scanner(System.in);
        System.out.print("Enter record no to display: ");
        int rec = input.nextInt();
        for (EmpDedup data : list) {
            if (data.getRecord() == rec) {
                System.out.println(data.getRecord() + "\t" + data.getFprint() + "\t" + data.getFid() + "\t");

                count++;

            }
        }
        System.out.println("The size of an linkedlist is: \t" + list.size());

        System.out.println("The number of  available record  is :" + count);

        System.out.println("The size of an linkedlist is: \t" + list.size());
        Scanner input1 = new Scanner(System.in);
        System.out.print("Enter record no to delete: ");// here i try to delete a particular record
        int rec1 = input1.nextInt();
        for (EmpDedup data : list) {
            if (data.getRecord() == rec1) {
                // System.out.println(data.getRecord()+"\t"+data.getFprint()+"\t"+data.getFid()+"\t");
                list.remove(data); // problem is here
                count++;

            }
        }
    }
}

you cannot operate in lists (add, remove... items) while you iterate on them. 在迭代它们时,你不能在列表中操作(添加,删除......项目)。 You have to use an Iterator 你必须使用迭代器

for(Iterator<EmpDedup> iter = list.iterator(); iter.hasNext();) {
    EmpDedup data = iter.next();
    if (data.getRecord() == rec1) {
        iter.remove();
    }
}

see http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html

请改用Iterator ,然后在Iterator上使用remove()方法

When you do this: 当你这样做:

list.remove(101);

you are calling this method, which will not serve your purpose. 你正在调用这种方法,这不符合你的目的。

You should rather use: 你应该使用:

list.remove(data);

You try to delete element with index 101, but you have only 4 items in list. 您尝试删除索引为101的元素,但列表中只有4个项目。 How it can delete element with index 101? 如何删除索引为101的元素?

If you want to delete element that is equals to EmpDedup(101,"entry1",20) than you have to pass in remove method this object. 如果要删除等于EmpDedup(101,“entry1”,20)的元素,则必须删除此方法中的remove方法。 And don't foget to redefine equals and hash code of EmpDedup. 并且不要忘记重新定义EmpDedup的equals和hash代码。

The code tries to remove element at index position 101, but there are only four items in the list. 代码尝试删除索引位置101处的元素,但列表中只有四个项目。

Use the following as a replacement of your code: 使用以下代码替换您的代码:

for( EmpDedup data : list)
{
   if( data.getRecord() == rec1 )
   {
        list.remove( data );     
         ++count;
    }
}

That's where a list object will be deleted. 这就是删除列表对象的位置。

for( EmpDedup data:list)
{
   if(data.getRecord()==rec1)
   {
        list.remove(data);     
         count++;

    }
 }

import java.util.Scanner; import java.util.Scanner;

// A complete working Java program to demonstrate deletion in singly // linked list class LinkedList { Node head; //一个完整的工作Java程序,用于演示单链//链表类中的删除LinkedList {Node head; // head of list //列表负责人

/* Linked list Node*/
class Node
{
    int data;
    Node next;
    Node(int d)
    {
        data = d;
        next = null;
    }
}

/* Given a key, deletes the first occurrence of key in linked list */
void deleteNode(int key)
{
    // Store head node
    Node temp = head, prev = null;

    // If head node itself holds the key to be deleted
    if (temp != null && temp.data == key)
    {
        head = temp.next; // Changed head
        return;
    }

    // Search for the key to be deleted, keep track of the
    // previous node as we need to change temp.next
    while (temp != null && temp.data != key)
    {
        prev = temp;
        temp = temp.next;
    }    

    // If key was not present in linked list
    if (temp == null) return;

    // Unlink the node from linked list
    prev.next = temp.next;
}

/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
    Node new_node = new Node(new_data);
    new_node.next = head;
    head = new_node;
}

/* This function prints contents of linked list starting from
    the given node */
public void printList()
{
    Node tnode = head;
    while (tnode != null)
    {
        System.out.print(tnode.data+" ");
        tnode = tnode.next;
    }
}

/* Drier program to test above functions. Ideally this function
should be in a separate user class. It is kept here to keep
code compact */
public static void main(String[] args)
{
    LinkedList llist = new LinkedList();

    llist.push(7);
    llist.push(1);
    llist.push(3);
    llist.push(2);

    System.out.println("\nCreated Linked list is:");
    llist.printList();

    Scanner sc = new Scanner(System.in);
    System.out.println("please enter input");
    int aa =sc.nextInt();
    llist.deleteNode(aa); // Delete node at position 4

    System.out.println("\nLinked List after Deletion at position :"+aa);


    llist.printList();

    System.out.println("adding element to the LinkedList");

    System.out.println("enter element");
    int dd = sc.nextInt();
    llist.push(dd);

    llist.printList();
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM