1、链表的初始化:节点、初始化链表
2、链表的基本操作:
查找
插入
删除
重置
package DataStructures;
/*
* LinkedList.
*/
import java.util.*;
class Linked_List {
/*
* an inner class.
*/
class Node {
/*
* the data.
*/
int data;
/*
* the reference to the next node.
*/
Node next;
/*
* the constructor.
*/
public Node(int paraValue) {
data = paraValue;
next = null;
}// Of the constructor
}// Of class Node
Node header;
/*
* Construct an empty Linkedlist.
*/
public Linked_List() {
header = new Node(0);
// header.next = null;//Redundant
}// Of the first constructor
@Override
public String toString() {
String resultString = "";
if (header.next == null) {
return "empty list";
} // Of if
Node tempNode = header.next;
while (tempNode != null) {
resultString += tempNode.data + " ";
tempNode = tempNode.next;
} // Of while
return resultString;
}// Of toString
/*
* Reset to empty.Free the space through garbage collection
*/
public void reset() {
header.next = null;
}
/*
* Locate the given value.
*/
public int locate(int paraValue) {
int tempPosition = -1;
Node tempNode = header.next;
int tempCurrentPosition = 0;
while (tempNode != null) {
if (tempNode.data == paraValue) {
tempPosition = tempCurrentPosition;
break;
} // Of if
tempNode = tempNode.next;
tempCurrentPosition++;
} // Of while
return tempPosition;
}// Of locate
/*
* insert a value to a position.
*/
public boolean insert(int paraPosition, int paraValue) {
Node tempNode = header;
Node tempNewNode;
for (int i = 0; i < paraPosition; i++) {
if (tempNode.next == null) {
System.out.println("The position " + paraPosition + " is illegal.");
return false;
} // Of if
tempNode = tempNode.next;
} // Of for
// Construct a new code.
tempNewNode = new Node(paraValue);
// Link them.
tempNewNode.next = tempNode.next;
tempNode.next = tempNewNode;
return true;
}// Of insert
public boolean delete(int paraPosition) {
if (header.next == null) {
System.out.println("Can't delete element from an empty list");
return false;
} // Of if
Node tempNode = header;
for (int i = 0; i < paraPosition; i++) {
if (tempNode.next.next == null) {
System.out.println("The position " + paraPosition + " is illegal.");
return false;
} // Of if
tempNode = tempNode.next;
} // Of for i
tempNode.next = tempNode.next.next;
return true;
}// Of delete
}
public class LinkedList {
public static void main(String[] args) {
Linked_List tempFirstList = new Linked_List();
System.out.println("Initialized, the list if: " + tempFirstList.toString());
for (int i = 0; i < 5; i++) {
tempFirstList.insert(0, i);
}
System.out.println("Inserted, the list is: " + tempFirstList.toString());
tempFirstList.insert(6, 9);
tempFirstList.delete(4);
tempFirstList.delete(2);
System.out.println("Deleted, the list is: " + tempFirstList.toString());
for (int i = 0; i < 5; i++) {
tempFirstList.delete(0);
System.out.println("Looped delete, the list is: " + tempFirstList.toString());
}
}
}