无傀儡节点链表增删改查及序列化实现
class Node2{
int val;
Node2 next;
public Node2(int val){
this.val=val;
}
}
class LinkedList{
private Node2 head=null;
public boolean add(int val){
if (head==null){
head=new Node2(val);
return true;
}
Node2 cur=head;
while(cur.next!=null){
cur=cur.next;
}
cur.next=new Node2(val);
return true;
}
public boolean delete(int val){
if(head==null)
return false;
Node2 pre=new Node2(0);
Node2 cur=head;
pre.next=cur;
while(cur!=null){
if (cur.val==val){
pre.next=cur.next;
return true;
}else{
pre=cur;
cur=cur.next;
}
}
return false;
}
public boolean modify(int elem,int val){
if (head==null)
return false;
Node2 cur=head;
while(cur!=null){
if(cur.val==val){
cur.val=elem;
return true;
}else{
cur=cur.next;
}
}
return false;
}
public boolean contain(int val){
if (head==null)
return false;
Node2 cur=head;
while(cur!=null){
if (cur.val==val){
return true;
}else{
cur=cur.next;
}
}
return false;
}
public String toString(){
StringBuffer res=new StringBuffer();
if(head==null)
return res.toString();
res.append("[");
Node2 cur=head;
while(cur!=null){
if(cur.next==null){
res.append(cur.val);
}else{
res.append(cur.val+",");
}
cur=cur.next;
}
res.append("]");
return res.toString();
}
}