单链表是最基本的数据结构,仔细看了很久终于搞明白了,差不每个部分,每个链都是node的一个对象。需要两个参数定位:一个是index,表示对象的方位。另一个是node的对象。
public class Node {
protected Node next;
protected int data;
public Node(int data){
this.data=data;
}
public void display(){
System.out.print(data+"");
}
}
public class myArrayList {
public Node first;//定义头结点
private int pos=0;//节点位置
public myArrayList(){
// this.first=null;
}
//插入一个头结点
public void addFirstNode(int data){
Node node=new Node(data);
node.next=first;
first=node;
}
//删除头结点
public Node deleteFirstNode(){
Node tempNode=first;
first=tempNode.next;
return tempNode;
}
// 在任意位置插入节点 在index的后面插入
public void add(int index, int data) {
Node node = new Node(data);
Node current = first;
Node previous = first;
while ( pos != index) {
previous = current;
current = current. next;
pos++;
}
node. next = current;
previous. next = node;
pos = 0;
}
// 删除任意位置的节点
public Node deleteByPos( int index) {
Node current = first;
Node previous = first;
while ( pos != index) {
pos++;
previous = current;
current = current. next;
}
if(current == first) {
first = first. next;
} else {
pos = 0;
previous. next = current. next;
}
return current;
}
public void displayAllNodes() {
Node current = first;
while (current != null) {
current.display();
System.out.println();
current = current. next;
}
}
}public class Main {
public static void main(String args[]){
myArrayList ls=new myArrayList();
ls.addFirstNode(15);
ls.addFirstNode(16);
ls.add(1, 144);
ls.add(2, 44);
ls.deleteByPos(1);
ls.displayAllNodes();
}
}
16
44
15
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/
原文:http://blog.csdn.net/buptgshengod/article/details/41681017