//节点
public class Node {
public int date;//数据域
public Node next;//指针域
public Node(int date ,Node next){
this.date = date;
this.next = next;
}
public Node() {
};
}
public class LinkNode {
public Node head;
private int len;
public LinkNode() {
init();
}
public void init() {
len=0;
head=new Node();
}
public void add(int ele) {
Node pnode = new Node(ele, null);
if(head.next == null) {
head.next=pnode;
len++;
}else {
Node t=head;
while(t.next!=null) {
t=t.next;
}
t.next=pnode;
len++;
}
print();
System.out.println("当前长度为:"+len);
}
public boolean del(int place) {
Node t=head;
if(place>len||place<0) {
return false;
}else if (place==len){
for(int i=1;i<place-1;i++) {
t=t.next;
}
t.next=null;
len--;
print();
System.out.println("当前长度为:"+len);
return true;
}else {
for(int i=1;i<place;i++) {
t=t.next;
}
t.next=t.next.next;
len--;
print();
System.out.println("当前长度为:"+len);
return true;
}
}
public boolean upd(int place,int ele) {
Node t=head;
if(place>len||place<0) {
return false;
}else {
for(int i=1;i<=place;i++) {
t=t.next;
}
t.date=ele;
print();
return true;
}
}
public boolean che(int place) {
Node t=head;
if(place>len||place<0) {
return false;
}else {
for(int i=1;i<=place;i++) {
t=t.next;
}
System.out.println("当前元素为:"+t.date);
return true;
}
}
public void print() {
Node t=head;
for(int i=1;i<=len;i++) {
t=t.next;
System.out.print(t.date);
System.out.print(" ");
}
System.out.println();
}
}
//链表测试
public class Main {
public static void main(String[] args) {
LinkNode l = new LinkNode();
l.add(1);
l.add(2);
l.add(3);
l.add(4);
l.del(2);
l.upd(1, 10);
l.che(1);
}
}