链表的一些操作2
package lianbiao;
public class Link<T> {
private Node<T> root;
private int foot;
private int count;
private class Node<T>{
private T data;
private Node nextNode;
public Node() {
}
public Node(T data) {
this.data = data;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public void addNode(Node<T> newNode){
if (this.getNextNode()==null){
this.setNextNode(newNode);
}else {
this.getNextNode().addNode(newNode);
}
}
public void printNode(){
System.out.println(this.data);
if (this.nextNode!=null){
this.nextNode.printNode();
}
}
public boolean containsNode(T data){
if (this.data.equals(data)){
return true;
}else {
if (this.nextNode==null){
return false;
}else {
return this.nextNode.containsNode(data);
}
}
}
public T getNodedata(int index){
if(foot++==index){
return this.data;
}else if (this.nextNode==null){
return null;
}else {
return (T)this.nextNode.getNodedata(index);
}
}
}
public void add(T data){
Node<T> newNode = new Node<>(data);
if (this.root==null){
this.root = newNode;
}else {
this.root.addNode(newNode);
}
count++;
}
public void print(){
if (this.root == null){
return;
}else {
this.root.printNode();
}
}
public int size(){
return this.count;
}
public boolean isEmpty(){
return this.count==0;
}
public boolean contains(T data){
if (this.root==null){
return false;
}else {
return this.root.containsNode(data);
}
}
public T get(int index){
if (this.root==null){
return null;
}if (index<0||index>count){
return null;
}
this.foot=0;
return this.root.getNodedata(index);
}
}
package lianbiao;
public class Test2 {
public static void main(String[] args) {
Link<String> link = new Link<>();
link.add("火车头");
link.add("1车厢");
link.add("2车厢");
link.add("3车厢");
link.add("4车厢");
link.add("车尾");
System.out.println(link.get(1));
System.out.println(link.get(2));
}
}
1车厢 2车厢
|