贴个练习的代码:
package com.liberty;
public class A {
public static void main(String[] args) {
Link link = new Link();
link.add("头");
link.add("身");
link.add("尾");
System.out.println(link.size());
}
}
class Link{
class Node{
private String data;//要保存的对象数据
private Node next;//要引用的下一个节点
public Node(String data){
this.data = data;
}
public void printNode(){
System.out.println(this.data);
if(this.next != null){
this.next.printNode();
}
}
public void addNode(Node newNode) {
if(this.next == null){
this.next = newNode;
}else{
this.next.addNode(newNode);
}
}
public boolean containsNode(String data) {
if(data.equals(this.data)){
return true;
}else{
if(this.next != null){
return this.next.containsNode(data);
}
}
return false;
}
public String getNode(int index) {
if(Link.this.foot++ == index){
return this.data;
}else{//我们之所以可能省略判断this.next部位null
//在于我们在前面设定了两个判断:1.index小于链表的count,而且index不为负数
return this.next.getNode(index);
}
}
public void setNode(int index,String data) {
if(index == Link.this.foot++){
this.data = data;
}else{
this.next.setNode(index,data);
}
}
public void removeNode(Node previous, String data) {
if(data.equals(this.data)){
previous.next = this.next;
}else {
this.next.removeNode(this, data);
}
}
}
//**********以上为内部类************
private Node head;//设置一个根节点
private int count = 0;//添加一个计数的int变量
public int foot = 0;//在Link类中创建一个索引的初始值
public void add(String data){
Node newNode = new Node(data);//创建一个Node对象
if(this.head == null){//注:data可以为空数据
this.head = newNode;
}else{
this.head.addNode(newNode);
}
this.count++;//每一次添加一个对象,就执行一次
}
public void print(){
if(this.head == null){
return;
}else{
this.head.printNode();
}
}
public int size(){
return this.count;//返回count的值
}
public boolean isEmpty(){
return this.count == 0;
}
public boolean contains(String data){
if(this.head == null || data == null){
return false;
}else{
return this.head.containsNode(data);
}
}
public String get(int index){//通过索引获取指定的内容
if(index > this.count || this.head == null || index < 0){
return null;
}else{
this.foot = 0;
return this.head.getNode(index);
}
}
public void set(int index,String data){
if(index > this.count || this.head == null || index < 0){
return;
}else{
this.foot = 0;
this.head.setNode(index,data);
}
}
public void remove(String data){
if(this.contains(data)){
if(data.equals(this.head.data)){
this.head = this.head.next;
}else{
this.head.next.removeNode(this.head,data);
}
this.count--;
}
}
}