单向链表的构造:
public class LinkList {
private Node headNode;
public void createLinked(int[] a) {
Node tailNode = new Node();
headNode = tailNode;
Node newNode;
for (int i = 0; i < a.length; i++) {
newNode = new Node();
newNode.setValue(a[i]);
tailNode.setNextNode(newNode);
newNode.setNextNode(null);
tailNode = newNode;
}
}
public void searchLink(int value) {
if (headNode == null) {
return;
}
Node nextNode = headNode.getNextNode();
while (nextNode != null) {
if (nextNode.getValue() == value) {
System.out.println("find the element");
break;
}
nextNode = nextNode.getNextNode();
}
if (nextNode == null) {
System.out.println("not found the element");
}
}
public void delteLink(int value) {
if (headNode == null) {
return;
}
Node preNode = headNode;
Node nextNode = headNode.getNextNode();
while (nextNode != null) {
if (nextNode.getValue() == value) {
preNode.setNextNode(nextNode.getNextNode());
System.out.println("delete the element success");
break;
}
preNode = nextNode;
nextNode = nextNode.getNextNode();
}
if (nextNode == null) {
System.out.println("no found the delete element");
}
}
public void insertLink(int pos, int value) {
if (headNode == null) {
return;
}
int count = 0;
boolean isSuccess = false;
Node currentNode = headNode;
while (currentNode != null) {
Node nextNode = currentNode.getNextNode();
if (pos == count) {
Node insertNode = new Node();
insertNode.setValue(value);
currentNode.setNextNode(insertNode);
insertNode.setNextNode(nextNode);
isSuccess = true;
break;
}
count++;
currentNode = nextNode;
}
if (isSuccess) {
System.out.println("insert the element success");
} else {
System.out.println("insert the element failed");
}
}
public void reverseLink() {
if (headNode == null) {
return;
}
Node preNode = headNode;
Node currentNode = headNode.getNextNode();
Node tempNode = currentNode;
while (currentNode != null) {
Node next = currentNode.getNextNode();
currentNode.setNextNode(preNode);
preNode = currentNode;
currentNode = next;
}
tempNode.setNextNode(null);
headNode.setNextNode(preNode);
}
public void displayLink() {
if (headNode == null) {
return;
}
Node nextNode = headNode.getNextNode();
System.out.print("Head -> ");
while (nextNode != null) {
System.out.print(nextNode.getValue() + " -> ");
nextNode = nextNode.getNextNode();
}
System.out.println("NULL");
}
public static void main(String[] args) {
int a[] = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = i * 2;
}
LinkList list = new LinkList();
list.createLinked(a);
list.displayLink();
// list.searchLink(20);
// list.delteLink(0);
// list.displayLink();
// list.insertLink(0, 1);
// list.displayLink();
list.reverseLink();
list.displayLink();
}
}
class Node {
private Node nextNode;
private int value;
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}