节点类
public class ListNode {
int data;//数据
ListNode next;//指针
public ListNode(int x){data=x;}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
节点操作:
public class ListNodeUtil { //链表
public static ListNode createHeadAddNodeList(int[] dataArray){//头插法插入数据
ListNode headNode=new ListNode(0);//创建头结点
headNode.setNext(null);
for(int i=0;i<dataArray.length;i++){
ListNode newNode=new ListNode(dataArray[i]);//赋值数据,创建新节点
newNode.setNext(headNode.getNext());//上一节点的指向赋值给下一节点的指向
headNode.setNext(newNode);//头结点指向尾部节点
}
return headNode;
}
public static ListNode createEndAddNodeList(int[] dataArray){//头插法插入数据
ListNode headNode=new ListNode(0);//创建头结点
headNode.setNext(null);
ListNode pointNode=headNode;//指针节点 一直指向尾节点
for(int i=0;i<dataArray.length;i++){
ListNode newNode=new ListNode(dataArray[i]);
newNode.setNext(pointNode.getNext());
pointNode.setNext(newNode);
pointNode=newNode;
}
return headNode;
}
public static void printHeadAddNodeList(ListNode start){
if(start!=null){
System.out.println(start.getData());
start=start.getNext();
printHeadAddNodeList(start);
}
}
public static void deleteNodeByIndex(ListNode startNode,int start,int end){//删除节点 start值输入0
if(startNode==null){return;}
if(start<end){//从上往下扫
start++;
startNode=startNode.getNext();
deleteNodeByIndex(startNode,start,end);//递归删除
}else{
startNode.setData(startNode.getNext().getData());
startNode.setNext(startNode.getNext().getNext());
}
}
public static void putNode(ListNode startNode,ListNode dataNode,int start,int end){//参数1开始节点 参数2数据节点
if(startNode==null){return;}
if(start<end){
start++;
startNode=startNode.getNext();
putNode(startNode,dataNode,start,end);
}else{
dataNode.setNext(startNode.getNext());
startNode.setNext(dataNode);
}
}
}
原文地址:http://blog.51cto.com/13919712/2165514