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 deleteLink( 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("not found the delete element");
}
}
public void insertLink(int pos, int value){
if( headNode == null )
return;
int count = 0;
boolean isSuccess = false;
Node currentNode = headNode;
Node nextNode;
while(currentNode != null)
{
nextNode = currentNode.getNextNode();
if( pos == count )
{
Node insertNode = new Node();
insertNode.setValue(value);
currentNode.setNextNode(insertNode);
insertNode.setNextNode(nextNode);
isSuccess = true;
break;
}
currentNode = nextNode;
count++;
}
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.deleteLink(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;
}
}
单向链表的构造
最新推荐文章于 2024-08-04 17:29:18 发布