Java实现链表的创建与数据的插入、删除、查找、打印:
import java.applet.Applet;
String airport;
ListNode link;
}
class LinkedList {
int length;
ListNode firstNode;
public int size() {
return length;
}
/* 在第一个节点之后插入新的第二个节点 */
public void insertNewSecondNode(String airportCode) {
if (length == 0) {
return;
}
ListNode newNode = new ListNode();
newNode.airport = airportCode;
newNode.link = firstNode.link;
firstNode.link = newNode;
length++;
}
/* 在链表中搜索某一个节点 */
public ListNode listSearch(String airportCode) {
ListNode N;
N = firstNode;
while (N != null) {
if (airportCode.endsWith(N.airport)) {
System.out.println(N.airport);
return N;
} else {
N = N.link;
}
}
System.out.println(N);
return N;
}
/* 删除最后一个节点 */
public void deleteLastNode() {
ListNode previousNode;
ListNode currentNode;
if (firstNode != null) {// 如果链表为空,则不进行任何处理
if (firstNode.link == null) {// 如果只有一个节点
firstNode = null;
length--;
}
else {// 否则链表有两个或者两个以上的节点
previousNode = firstNode;
currentNode = firstNode.link;
while (currentNode.link != null) {
previousNode = previousNode.link;
currentNode = currentNode.link;
}
previousNode.link = null;// previousNode指向倒数第二个节点,将其指向空则删除了末端节点
length--;
}
}
}
/* 在链表末端插入一个新的节点 */
public void insertNewLastNode(String airportNode) {
ListNode N = new ListNode();
N.airport = airportNode;
N.link = null;
if (firstNode == null) {
firstNode = N;
} else {
ListNode P = firstNode;
while (P.link != null) {
P = P.link;// P指向末端节点
}
P.link = N;// 将N节点连接到末端节点
}
length++;
}
/* 打印链表节点 */
public void print() {
ListNode N;
N = firstNode;
while (N != null) {
System.out.println(N.airport);
N = N.link;
}
}
}
/*测试类*/
public class LinkList extends Applet {
private static final long serialVersionUID = 1L;
public void init() {
LinkedList L = new LinkedList();
System.out.println("创建链表:");
L.insertNewLastNode("ABC");
L.insertNewLastNode("DEF");
L.insertNewLastNode("GHI");
L.print();
System.out.println("插入第2个节点:");
L.insertNewSecondNode("JKL");
L.print();
System.out.println("删除末节点:");
L.deleteLastNode();
L.print();
System.out.println("查找节点:");
L.listSearch("ABC");
}
}
本文介绍了一个简单的Java链表实现,包括节点的插入、删除、查找和打印等基本操作,并通过一个测试类展示了如何使用这些方法。
4942

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



