add メソッドを使用して、目的のインデックスに要素を追加します。しかし、最後に追加しています。目的のインデックスに要素を追加したい。これでどうにかできる。可能ですか?エンドポインターなし。
import java.util.*;
class List {
Customer listPtr;
int index;
public void add(Customer customer) {
Customer temp = customer;
if (listPtr == null) {
listPtr = temp;
index++;
} else {
Customer x = listPtr;
while (x.next != null) {
x = x.next;
}
x.next = temp;
index++;
}
}
public void add(int index, Customer customer) {
int size = size();
while (size != -1) {
size--;
if (size == index) {
System.out.println(size + ":" + index);
add(customer);
}
}
}
public void removeFirst() {
Customer temp = listPtr;
if (listPtr != null) {
listPtr = temp.next;
}
}
public void removeLast() {
Customer temp = listPtr;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
index--;
}
public void removeAll() {
Customer temp = listPtr;
while (temp != null) {
listPtr = temp.next;
temp = temp.next;
}
}
public int size() {
int size = 0;
Customer temp = listPtr;
while (temp != null) {
size++;
temp = temp.next;
}
return size;
}
public void printList() {
Customer temp = listPtr;
while (temp != null) {
System.out.println(temp);
temp = temp.next;
}
}
}
class DemoList {
public static void main(String args[]) {
List list = new List();
Customer c1 = new Customer("10011", "Sam");
Customer c2 = new Customer("10012", "Jason");
Customer c3 = new Customer("10013", "Arnold");
Customer c4 = new Customer("10014", "Bob");
Customer c5 = new Customer("10015", "Tom");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
list.add(2, c5);
System.out.println(list.size());
list.printList();
}
}
class Customer {
String id;
String name;
Customer next;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id + " : " + name;
}
public boolean equals(Object ob) {
Customer c = (Customer) ob;
return this.id.equals(c.id);
}
}