CirSinglyList循环单链表类的成员方法void removeAll(CirSinglyList list) //集合差,this-=list
public class CirSinglyList<T> {
public Node<T>head; //头指针
public CirSinglyList() //构造空循环单链表
{
this.head=new Node<T>();
head.next=head;
}
public CirSinglyList(T[] values) //构造循环单链表,由values数组提供元素
{
this(); //构造空单链表,只有头结点
Node<T> rear = this.head; //rear指向单链表的最后一个结点
for (int i = 0; i < values.length; i++) //若values.length==0,构造空链表
{ rear.next = new Node<T>(values[i], this.head); //尾插入,创建结点链入rear结点之后
rear = rear.next; //rear指向新的链尾结点
}
}
public Node<T> search(T key) //查找返回首个与key相等元素结点,查找不成功返回null
{
Node<T> q = this.head.next;
while (q != head) //遍历单链表,查找与key元素相等的结点q
{
if (q.data.equals(key) ) //判断结点q引用的对象元素是否与key相等
{
return q;
}
q = q.next;
}
return null;
}
public String toString() //返回单链表所有元素的描述字符串,形式为"(,)"。覆盖Object类的toString()方法,O(n)
{
String str = this.getClass().getName() + "("; //返回类名
for (Node<T> p = this.head.next; p != head; p = p.next) //p遍历单链表 {
str += p.data.toString(); //p结点数据域的描述字符串给str
if (p.next != head) {
str += ","; //不是最后一个结点时,加分隔符
}
}
return str + ")";
}
public void removeAll(CirSinglyList<T> list)
{
Node<T> front = this.head;
Node<T> p = this.head.next;
while (p!=head){
Node<T> s =list.search(p.data); //调用search(x)方法,查找成功,返回元素x对应的结点;失败返回null
if (s!=null)
{ //查找成功
p = p.next; //p向后移
front.next = front.next.next; //删除查找到的结点
}
else { //p和front都向后移动
p=p.next;
front=front.next;
}
}
}
public static void main(String[] args)
{
String[] strings1 = {"a", "b", "c", "d", "e", "f", "g", "h"};
CirSinglyList values=new CirSinglyList(strings1);
String[] strings2= { "b", "c", "d", "f","m"};
CirSinglyList list=new CirSinglyList(strings2);
values.removeAll(list);
System.out.println("values与list的集合差:"+values.toString());
}
}
values与list的集合差:CirSinglyList(a,e,g,h)
- 单链表结点自己写一下,抄书很简单