两个链表集之间的联合和交集,java

时间:2013-01-29 06:48:01

标签: java linked-list union

我试图将方法写成“联合”,可以描述:如果A,B,C是集合,则形式为C = A.union(B)。 Union返回一个Set,其中包含集合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创建节点并遍历它?,可能有比较方法来比较union方法之外的2个集合?

请帮忙。谢谢大家。

1 个答案:

答案 0 :(得分: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
}