2

我试图编写可以描述为“联合”的方法:如果 A、B、C 是集合,则具有 C = A.union(B) 的形式。Union 返回一个集合,其中包含集合 A 和 B 中的所有元素,但只列出一次重复项。

我对这个方法的想法是遍历集合A并将其所有元素添加到联合集合中,然后遍历集合B,如果集合B的元素已经存在于联合集合中,则不要将其插入结果,否则插入全部归并集。

这对于像我这样的初学者来说很复杂,因为我想将所有 3 个列表都包含在方法中(我得到了一堆错误)。我已经在我的 SLinkedList 类中编写了一些方法来检查和添加元素,但是参数从节点获取一个对象

/** Singly linked list .*/
public class SLinkedList {

  protected Node head;   // head node of the list
  protected int size;    // number of nodes in the list

  /** Default constructor that creates an empty list */
  public SLinkedList() {
    head = new Node(null, null); // create a dummy head
    size = 0; 

 // add last
  public void addLast(Object data) {
      Node cur = head;
      // find last node
      while (cur.getNext() != null) {
          cur = cur.getNext();
      }
      // cur refers to the last node
      cur.setNext(new Node(data, null));
      size++;
  } 

 // contain method to check existing elements
  public boolean contain (Object target) {
      boolean status = false;
      Node cursor;
      for (cursor = head; cursor != null; cursor = cursor.getNext()) {
          if (target.equals(cursor.getElement())) {
              status = true;
          }       
      }   
      return status;
  }

  public SLinkedList union (SLinkedList secondSet) {
      SLinkedList unionSet = new SLinkedList();
      secondSet = new SLinkedList();
      Node cursor;
      for(cursor = head.getNext(); cursor != null; cursor = cursor.getNext()) {
          unionSet.addLast(cursor.getElement());
          // traverse secondSet, if an element is existed in either set A or union
              // set, skip, else add to union set
          }
      }
    return unionSet;
  }


  }

节点类

/** Node of a singly linked list of strings. */
public class Node {

  private Object element;   // we assume elements are character strings
  private Node next;

  /** Creates a node with the given element and next node. */
  public Node(Object o, Node n) {
    element = o;
    next = n;
  }

  /** Returns the element of this node. */
  public Object getElement() { return element; }

  /** Returns the next node of this node. */
  public Node getNext() { return next; }

  // Modifier methods:
  /** Sets the element of this node. */
  public void setElement(Object newElem) { element = newElem; }

  /** Sets the next node of this node. */
  public void setNext(Node newNext) { next = newNext; }

}

*更新* 问题是如果涉及第二个列表public SLinkedList union (SLinkedList secondSet),我应该使用什么语法来遍历集合B并检查集合B的元素是否已经存在于结果中,然后不要将其插入结果,否则插入。我需要为集合 B 创建一个节点并遍历它吗?可能有一种比较方法来比较联合方法之外的 2 个集合?

请帮忙。谢谢大家。

4

1 回答 1

1
SLinkedList unionSet = null; // need a new SLinkedList() here
Node cursor;
for(cursor = head.getNext(); cursor != null; cursor = cursor.getNext()) {
    unionSet.addLast(cursor.getElement()); // NPE because unionSet is null
}
于 2013-01-29T06:51:34.223 回答