双向循环链表返回元素x第一次出现在双向循环链表中的位置号Java代码
时间: 2024-04-15 17:27:42 浏览: 10
以下是返回元素x第一次出现的位置号的Java代码示例:
```java
public class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
public class DoublyLinkedList {
Node head;
public void addNode(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
head.next = head;
head.prev = head;
} else {
Node last = head.prev;
last.next = newNode;
newNode.prev = last;
newNode.next = head;
head.prev = newNode;
}
}
public int findFirstOccurrence(int x) {
if (head == null) {
return -1; // List is empty
}
Node current = head;
int position = 0;
do {
if (current.data == x) {
return position;
}
current = current.next;
position++;
} while (current != head);
return -1; // Element not found
}
}
// Usage example
public class Main {
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.addNode(4);
list.addNode(5);
int x = 3;
int position = list.findFirstOccurrence(x);
if (position != -1) {
System.out.println("Element " + x + " found at position " + position);
} else {
System.out.println("Element " + x + " not found in the list");
}
}
}
```
这段代码定义了一个双向循环链表的实现,并提供了一个方法 `findFirstOccurrence`,该方法用于返回元素 x 第一次出现在双向循环链表中的位置号。你可以根据需要进行修改和扩展。