链表数据结构结点:
package list;
/**
* @packagname:PACKAGE_NAME
* @classname:LinkedNode
* @date:2017/1/22
* @author:cullinans
* @des:链表的结点结构
*/
public class LinkedNode <T>{
T data;
LinkedNode<T> next;
}
利用工厂设计模式来生成链表结点实例对象:
package list;
/**
* @packagname:PACKAGE_NAME
* @classname:NodeFactory
* @date:2017/1/22
* @author:cullinans
* @des:生成结点的工厂类
*/
public class NodeFactory {
public static LinkedNode createLinkedNode(){
return new LinkedNode();
}
}
列表的一些相关操作:(以下代码在Intellij Idea 2016编译通过,可以通过以下注释的一些打印语句来验证方法的正确性)
package list;
public class TestLinkedList<T> {
LinkedNode node = null;
public TestLinkedList(LinkedNode node) {
this.node = node;
node.next=null;
}
public String createLinkedList(TestLinkedList l, int i,T[] data) {
LinkedNode<T> tempnode=l.node;
for(int j=0;j<i;j++){
LinkedNode newnode = NodeFactory.createLinkedNode();
newnode.data=data[j];
tempnode.next=newnode;
tempnode=newnode;
}
return "创建完毕";
}
public T getElem(TestLinkedList l, int i) {
if(i<0){
return null;
}
LinkedNode<T> p=l.node;
int j=0;
while(p!=null && j<i){
p=p.next;
++j;
}
if(j==i) {
return p.data;
}else{
return null;
}
}
public int listInsert(TestLinkedList l, LinkedNode<T> t, int i) {
if(i<0){
return -1;
}
LinkedNode<T> tempPoint=null;
tempPoint=l.node;
int j=0;
while(tempPoint!=null && j<i){
if(j==i-1){
t.next=tempPoint.next;
tempPoint.next=t;
break;
}
tempPoint = tempPoint.next;
j++;
}
if(j==i){
t.next=tempPoint;
l.node=t;
return 0;
}else{
return -1;
}
}
public int listDelete(TestLinkedList l, int i) {
if(i<0){
return -1;
}
int j=0;
LinkedNode<T> tempPoint=null;
tempPoint=l.node;
while(tempPoint!=null && j<i){
if(j==i-1){
tempPoint.next=tempPoint.next.next;
break;
}else {
tempPoint = tempPoint.next;
j++;
}
}
if(j==i){
tempPoint=tempPoint.next;
}
return 0;
}
public int clearList(TestLinkedList l) {
LinkedNode<T> tempNode;
tempNode=l.node;
tempNode.next=null;
tempNode.data=null;
return 0;
}
public static void main(String[] args){
LinkedNode linkedNode = new LinkedNode();
linkedNode.data= "one";
linkedNode.next=null;
TestLinkedList<String> testLinkedList=new TestLinkedList<String>(linkedNode);
String[] test=new String[]{"a","b","c"};
testLinkedList.createLinkedList(testLinkedList,3,test);
LinkedNode<String> insertNode=new LinkedNode<String>();
insertNode.data="insert";
insertNode.next=null;
System.out.println(testLinkedList.listInsert(testLinkedList,insertNode,0));
System.out.println(testLinkedList.getElem(testLinkedList,0));
System.out.println(testLinkedList.getElem(testLinkedList,1));
System.out.println(testLinkedList.getElem(testLinkedList,2));
System.out.println(testLinkedList.getElem(testLinkedList,3));
}
}