1.链式结构
public class LinkedList {
private Node head;
private int size;
public LinkedList() {
head = null;
size = 0;
}
public Object getElement(int i) {
Node temp = head;
int j = 0;
while (temp != null && j < i) {
temp = temp.next;
j++;
}
if (temp == null || j > i) {
return null;
}
return temp.data;
}
public void add(Object data) {
if (head == null) {
head = new Node(data);
size++;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(data);
size++;
}
}
public boolean delete(int index) {
if (size == 0) {
return false;
}
Node previous = head;
Node current = head;
int j = 0;
while (current != null && j < index) {
previous = current;
current = current.next;
j++;
}
if (current == null || j > index) {
return false;
}
previous.next = current.next;
current.next = null;
size--;
return true;
}
public void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data);
temp = temp.next;
}
System.out.println("---------------");
}
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.display();
linkedList.delete(1);
linkedList.display();
System.out.println(linkedList.getElement(2));
System.out.println(linkedList.getElement(5));
}
}
class Node {
Object data;
Node next;
public Node(Object data) {
this.data = data;
this.next = null;
}
}