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

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

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

/** 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的元素,则不要将其插入到result中,否则插入。我是否需要为集合B创建一个节点并遍历它?在并集方法之外可能有一个比较方法来比较这两个集合?

请帮忙。谢谢大家

最佳答案

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
}

10-07 15:55