JAVA 实现一个链表
class Node {
public int data;
public Node next;
public Node() {
data = 0;
next = null;
}
public Node(int d, Node n) {
data = d;
next = n;
}
public void setData(int data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
Node getNext() {
return next;
}
int getData() {
return data;
}
}
class LinkList {
private Node head, end, current;
LinkList() {
head = end = current = null;
}
void print() {
if (head == null) {
System.out.println("The list is empty!");
System.exit(0);
} else {
current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
}
void insertTail(int d) {
Node newnode = new Node(d, null);
if (head == null) {
head = newnode;
end = newnode;
newnode.next = null;
} else {
end.next = newnode;
end = newnode;
end.next = null;
}
}
void insertHead(int d) {
Node newnode = new Node(d, null);
if (head == null) {
head = newnode;
end = newnode;
newnode.next = null;
} else {
newnode.next = head;
head = newnode;
}
}
int length() {
if (head == null)
return 0;
else {
int len = 0;
current = head;
while (current != null) {
len++;
current = current.next;
}
return len;
}
}
int search(int d) {
int index;
if (head == null) {
System.out.println("Search in a empty list is illeagal!");
System.exit(1);
} else {
index = 0;
current = head;
while (current != null) {
index++;
if (current.data == d)
break;
current = current.next;
}
if(current != null)
return index;
}
return -1;
}
public static void main(String args[]) {
LinkList one = new LinkList();
for (int i = 10; i < 20; i++)
one.insertTail(i);
one.print();
System.out.println();
System.out.println(one.search(16));
}
}