java单向链表的简单实现

package com.fy.api.server.demo2;


public class LkList {

private Node head;

private Node current;

public class Node {

public int data;

public Node next;

public Node (int data) {
this.data = data;
}

public void add (Node node) {
if(head == null) {
head = node;
current = head;
}
if (current.next == null) {
current.next = node;
} else {
current = current.next;
current.add(node);

}
}

}

public void addNode (Node node) {
if (node == null) {
System.out.println("can't add a null element!");
return;
}
current = head;
if (head == null) {
//System.out.println("throw null pointer exception!");
head = node;
return;
}
this.current.add(node);
}

public void showNodes () {
this.current = head;
int count = 0;
System.out.print("[");
while(this.current!=null){
System.out.print(count==0?this.current.data: ","+this.current.data );
count ++;
this.current = this.current.next;
}
System.out.print("]");
System.out.println();
}

public int len () {
this.current = head;
if (this.current == null) {
return 0;
}

if (this.current.next == null) {
return 1;
}
int len = 1;
while (this.current.next !=null) {
len++;
this.current = this.current.next;
}
return len;
}

public void deleteNode (int index) {
if (index <0 || index>=this.len()) {
System.out.println("exception outof list bounds!");
return;
}

if (index == 0) {
head = head.next;
if (head!=null) {
current = head;
}
}

int len = 1;
Node tmp = head;
while (tmp.next != null) {
if (index == len++) {
tmp.next = tmp.next.next;
return;
}
tmp = tmp.next;
}
}

public static void main (String []args) {
LkList lk = new LkList();
Node head = lk.new Node(1);
lk.addNode(head);
lk.addNode(lk.new Node(2));
lk.addNode(lk.new Node(3));
lk.addNode(lk.new Node(4));
System.out.println(lk.len());
lk.showNodes();
lk.deleteNode(0);
lk.showNodes();
lk.addNode(lk.new Node(5));
lk.showNodes();
lk.deleteNode(3);;
lk.showNodes();
System.out.println(lk.len());
}

}

原文地址:https://www.cnblogs.com/playburst/p/7998128.html