链表

public class MyLinked {
private Node head = null;
private Node last = null;
private int len = 0;

/**
* 添加,到尾部
*
* @param s
*/
public void add(String s) {
Node n = new Node(s);
if (head == null) {
head = n;
last = n;
} else {
last.next = n;
last = n;
}
len++;

}

/**
* 插入到中间
*
* @param s
* @param index
*/
public void add(String s, int index) {
if (index < 0 || index >= len) {
System.err.println("下标越界");
}
Node n = new Node(s);
Node n1 = getNodeByIndex(index - 1);// 前一个节点
Node n2 = getNodeByIndex(index);// 后一个节点
if (index == 0) {
n.next = n2;
head = n;
} else {
n1.next = n;
n.next = n2;
}
len++;

}

/**
* 删除
*
* @param index
*/
public void remove(int index) {
if (index < 0 || index >= len) {
System.err.println("下标越界");
}
Node n=getNodeByIndex(index);
Node n1=getNodeByIndex(index-1);
Node n2=getNodeByIndex(index+1);
if(index==0) {
n.next=null;
head=n2;
}else {
n1.next=n2;
n.next=null;
}
len--;
}

/**
* 修改
*
* @param index
* @param s
*/
public void update(int index, String s) {
Node n=getNodeByIndex(index);
n.data=s;
}

/**
* 查找栈的大小
*
* @return
*/
public int size() {
return len;
}

/**
* 得到数据
*
* @return
*/
public String getData(int index) {
Node n = getNodeByIndex(index);
if (n != null) {
return n.data;
}
return null;
}

public Node getNodeByIndex(int index) {
Node n = head;
for (int i = 0; i < index; i++) {
n = n.next;
}
if (n != null) {
return n;
}
return null;
}

private class Node {
String data; // 数据
Node next; // 对下一个节点的引用

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

}

    链表

    

     

    

      

      

      

 

posted @ 2019-08-07 21:35  热爱生活,热爱编程  阅读(135)  评论(0编辑  收藏  举报