QNode
package com.qipan;
public class QNode {
private String data = null;
private QNode nextNode = null;
public QNode(){
}
public String Data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public QNode NextNode() {
return nextNode;
}
public void setNextNode(QNode nextNode) {
this.nextNode = nextNode;
}
}
QList
package com.qipan;
public class QList {
private QNode headNode = null;
private QNode tailNode = null;
private int size = 0;
public QList() {
}
public void add(String data) {
if (headNode == null && tailNode == null) {
headNode = new QNode();
QNode node = new QNode();
node.setData(data);
headNode.setNextNode(node);
tailNode = node;
} else {
QNode node = new QNode();
node.setData(data);
tailNode.setNextNode(node);
tailNode = node;
}
size++;
}
public void delete(int i) {
if(i<0 || i>size-1){
throw new IndexOutOfBoundsException("索引越界!");
}
if (headNode != null) {
int pos = 0;
QNode tempQNode = headNode;
QNode previousQNode = headNode;
while ((tempQNode = previousQNode.NextNode()) != null) {
if(pos++==i){
previousQNode.setNextNode(tempQNode.NextNode());
}else{
previousQNode = tempQNode;
}
}
}
size--;
}
public void insert(int i, String data) {
if(i<0 || i>size-1){
throw new IndexOutOfBoundsException("索引越界!");
}
if (headNode != null) {
int pos = 0;
QNode tempQNode = headNode;
QNode previousQNode = headNode;
while ((tempQNode = previousQNode.NextNode()) != null) {
if(pos++==i){
QNode node = new QNode();
node.setData(data);
node.setNextNode(tempQNode);
previousQNode.setNextNode(node);
}else{
previousQNode = tempQNode;
}
}
}
size++;
}
public QNode HeadNode() {
return headNode;
}
public void setHeadNode(QNode headNode) {
this.headNode = headNode;
}
public QNode TailNode() {
return tailNode;
}
public void setTailNode(QNode tailNode) {
this.tailNode = tailNode;
}
public int Size() {
return size;
}
public void setSize(int size) {
this.size = size;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer("[");
if (headNode != null) {
QNode tempQNode = headNode;
while ((tempQNode = tempQNode.NextNode()) != null) {
sb.append(tempQNode.Data() + ",");
}
}
return sb.deleteCharAt(sb.length() - 1).toString()+"]";
}
}
JStarter
package com.qipan;
/**
* 演示链式存储结构
* @author zhangrenyang
*/
public class JStarter {
public static void main(String[] args) {
QList qList = new QList();
qList.add("a");
qList.add("b");
qList.add("c");
qList.delete(1);
qList.insert(1, "b");
qList.add("d");
qList.add("e");
qList.insert(4,"f");
System.out.println(qList);
}
}