在Java编程语言中,为了增强循环单链表的功能,我们可以在CirSinglyList类中添加一个新的公共方法search(CirSinglyList pattern)。此方法的主要功能是查找并返回当前列表中第一个与给定模式匹配的子列表。
首先,定义一个内部节点类Node,用于存储单链表中的元素:
```java
public class Node {
public T data;
public Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
public Node() {
this(null, null);
}
@Override
public String toString() {
return data.toString();
}
}
```
接下来,定义循环单链表类CirSinglyList,并实现search方法:
```java
public class CirSinglyList {
private Node head;
public CirSinglyList() {
head = new Node();
head.next = head;
}
public CirSinglyList(T[] values) {
this();
Node rear = head;
for (T value : values) {
rear.next = new Node(value, null);
rear = rear.next;
}
rear.next = head;
}
public boolean isEmpty() {
return head.next == head;
}
public T get(int index) {
if (index <0) return null;
Node p = head.next;
int count = 0;
while (p != head && count p = p.next;
count++;
}
return (p != head) ? p.data : null;
}
public String toString() {
StringBuilder str = new StringBuilder(this.getClass().getName() + "(");
Node p = head.next;
while (p != head) {
str.append(p.data.toString());
if (p.next != head) str.append(", ");
p = p.next;
}
return str.append(")").toString();
}
public CirSinglyList search(CirSinglyList pattern) {
Node p = head.next;
Node q = pattern.head.next;
while (p != head) {
Node tempP = p;
Node tempQ = q;
boolean match = true;
while (tempQ != pattern.head) {
if (tempP == head || !tempP.data.equals(tempQ.data)) {
match = false;
break;
}
tempP = tempP.next;
tempQ = tempQ.next;
}
if (match) {
CirSinglyList result = new CirSinglyList<>();
Node current = p;
while (current != head && !current.data.equals(p.data)) {
result.add(current.data);
current = current.next;
}
return result;
}
p = p.next;
}
return null;
}
}
```
上述代码实现了循环单链表的基本操作以及模式匹配的搜索功能。通过这种方式,可以有效地在循环单链表中查找特定的子列表。