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));
}
}
本文介绍了一个简单的JAVA链表实现,包括节点定义、链表的基本操作如插入、删除、搜索等,并提供了一个完整的运行示例。

被折叠的 条评论
为什么被折叠?



