双向链表做通讯录java_双向链表(java代码实现)
时间: 2023-07-10 19:38:24 浏览: 56
下面是一个简单的双向链表实现通讯录的 Java 代码:
```java
public class Contact {
private String name;
private String phone;
private Contact prev;
private Contact next;
public Contact(String name, String phone) {
this.name = name;
this.phone = phone;
this.prev = null;
this.next = null;
}
public void setPrev(Contact prev) {
this.prev = prev;
}
public void setNext(Contact next) {
this.next = next;
}
public Contact getPrev() {
return prev;
}
public Contact getNext() {
return next;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
}
public class ContactList {
private Contact head;
private Contact tail;
public ContactList() {
head = null;
tail = null;
}
public void addContact(String name, String phone) {
Contact newContact = new Contact(name, phone);
if (head == null) {
head = newContact;
tail = newContact;
} else {
tail.setNext(newContact);
newContact.setPrev(tail);
tail = newContact;
}
}
public void removeContact(String name) {
Contact current = head;
while (current != null) {
if (current.getName().equals(name)) {
if (current == head) {
head = current.getNext();
if (head != null) {
head.setPrev(null);
}
} else if (current == tail) {
tail = current.getPrev();
if (tail != null) {
tail.setNext(null);
}
} else {
current.getPrev().setNext(current.getNext());
current.getNext().setPrev(current.getPrev());
}
break;
}
current = current.getNext();
}
}
public void printContacts() {
Contact current = head;
while (current != null) {
System.out.println(current.getName() + " - " + current.getPhone());
current = current.getNext();
}
}
}
```
这个实现中,`Contact` 类表示一个联系人,包含姓名、电话号码和前后指针。`ContactList` 类表示一个联系人列表,维护头尾指针,并提供添加、删除和打印联系人的方法。