//A1.java
public class A1 {
public static void main(String[] args) {
SimpleLinkList list=new SimpleLinkList();
list.Insert(1, "a");
list.print();
list.Insert(1, "b");
list.print();
System.out.println(list.GetElem(2));
System.out.println(list.GetElemPtr(2).data);
list.Insert(1, "c");
list.print();
list.Insert(1, "d");
list.print();
list.SetElem(1, "x");
System.out.println(list.Length());
list.Insert(1, "d");
list.print();
list.Delete(1);
list.print();
list.Insert("y");
list.print();
}
}
class Node {
String data = null;
Node next = null;
public Node() {
}
public Node(String d, Node n) {
data = d;
next = n;
}
}
class SimpleLinkList{
Node head;
public SimpleLinkList(){
head=new Node();
}
public Node GetElemPtr(int p){
if(p<0 || p>Length()){
return null;
}
Node temp=head;
for(int i=0;temp!=null && i<p;i++){
temp=temp.next;
}
return temp;
}
public int Length(){
int count=0;
for(Node temp=head.next;temp!=null;temp=temp.next){
count++;
}
return count;
}
public boolean Empty(){
return Length()==0;
}
public String GetElem(int p){
Node temp=GetElemPtr(p);
if(temp==null || p==0){
return null;
}
return GetElemPtr(p).data;
}
public void SetElem(int p,String d){
Node temp=GetElemPtr(p);
if(temp!=null && p!=0){
temp.data=d;
}
}
public void Insert(int p,String d){
Node temp=GetElemPtr(p-1);
if(temp!=null){
temp.next=new Node(d,temp.next);
}
}
public void Insert(String d){
GetElemPtr(Length()).next=new Node(d,null);
}
public void Delete(int p){
Node temp=GetElemPtr(p);
if(temp!=null && p!=0){
GetElemPtr(p-1).next=temp.next;
}
}
public void print(){
for(Node temp=head.next;temp!=null;temp=temp.next){
System.out.print(temp.data+" ");
}
System.out.println();
}
}
运行结果:
a
b a
a
a
c b a
d c b a
4
d x c b a
x c b a
x c b a y