Uploaded by Truong Nguyen Tien Dat (K18 DN)

AdressBook

advertisement
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to
change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this
template
*/
/**
*
* @author ddattt
*/
public class AddressBook {
private Node head, tail;
private class Node {
String name;
String phoneNumber;
String address;
Node next, prev;
Node(String name, String phoneNumber, String address) {
this.name = name;
this.phoneNumber = phoneNumber;
this.address = address;
}
}
/**
* Constructs an empty AddressBook with no entries.
*/
public AddressBook() {
head = null;
tail = null;
}
public void addEntry(String name, String phoneNumber, String address) {
Node newNode = new Node(name, phoneNumber, address);
if (head == null) { // If the address book is empty
head = newNode; // Set the new node as the head
tail = newNode; // Set the new node as the tail
} else {
tail.next = newNode; // Set the next reference of the tail to the new
node
newNode.prev = tail; // Set the previous reference of the new node to
the tail
tail = newNode; // Update the tail to the new node
}
}
public void deleteEntry(String name) {
Node current = head; // Start from the head of the list
while (current != null) { // Iterate through the list
if (current.name.equals(name)) { // If the current node's name
matches the specified name
if (current.prev != null) { // If the current node has a previous
node
current.prev.next = current.next; // Set the next reference
of the previous node to the next node
} else {
head = current.next; // Set the next node as the new head
}
if (current.next != null) { // If the current node has a next
node
current.next.prev = current.prev; // Set the previous
reference of the next node to the previous node
} else {
tail = current.prev; // Set the previous node as the new tail
}
return;
}
current = current.next; // Move to the next node
}
}
public void updateEntry(String name, String phoneNumber, String address) {
Node current = head; // Start from the head of the list
while (current != null) { // Iterate through the list
if (current.name.equals(name)) { // If the current node's name
matches the specified name
current.phoneNumber = phoneNumber; // Update the phone number of
the current node
current.address = address; // Update the address of the current
node
return;
}
current = current.next; // Move to the next node
}
}
public void printAddressBook() {
Node current = head; // Start from the head of the list
while (current != null) { // Iterate through the list
System.out.println("Name: " + current.name + ", Phone Number: " +
current.phoneNumber + ", Address: " + current.address); // Print the details of
the current node
current = current.next; // Move to the next node
}
}
}
Download