此代碼僅供參考
package com
//節點類
public class Node {
protected Node next; //指針域
protected int data;//數據域
public Node( int data) {
this
}
//顯示此節點
public void display() {
System
}
}
package com
//單鏈表
public class LinkList {
public Node first; // 定義一個頭結點
private int pos =
public LinkList() {
this
}
// 插入一個頭節點
public void addFirstNode( int data) {
Node node = new Node(data)
node
first = node;
}
// 刪除一個頭結點
public Node deleteFirstNode() {
Node tempNode = first;
first = tempNode
return tempNode;
}
// 在任意位置插入節點 在index的後面插入
public void add(int index
Node node = new Node(data)
Node current = first;
Node previous = first;
while ( pos != index) {
previous = current;
current = current
pos++;
}
node
previous
pos =
}
// 刪除任意位置的節點
public Node deleteByPos( int index) {
Node current = first;
Node previous = first;
while ( pos != index) {
pos++;
previous = current;
current = current
}
if(current == first) {
first = first
} else {
pos =
previous
}
return current;
}
// 根據節點的data刪除節點(僅僅刪除第一個)
public Node deleteByData( int data) {
Node current = first;
Node previous = first; //記住上一個節點
while (current
if (current
return null;
}
previous = current;
current = current
}
if(current == first) {
first = first
} else {
previous
}
return current;
}
// 顯示出所有的節點信息
public void displayAllNodes() {
Node current = first;
while (current != null) {
current
current = current
}
System
}
// 根據位置查找節點信息
public Node findByPos( int index) {
Node current = first;
if ( pos != index) {
current = current
pos++;
}
return current;
}
// 根據數據查找節點信息
public Node findByData( int data) {
Node current = first;
while (current
if (current
return null;
current = current
}
return current;
}
}
package com
//測試類
public class TestLinkList {
public static void main(String[] args) {
LinkList linkList = new LinkList()
linkList
linkList
linkList
//
linkList
linkList
linkList
linkList
// Node node = linkList
// System
// linkList
// node = linkList
// System
// linkList
// linkList
Node node = linkList
// Node node = linkList
System
linkList
Node node
System
Node node
System
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26549.html