/*
链表的增、改、查、删
*/
public class LinkLIST {
int size;//节点个数
NewNode head;//头节点地址
class NewNode{
int val;//存放具体数据
NewNode next;//存下一个节点的地址
public NewNode(int val){
this.val=val;
}
}
public void addFirst(int val){//头插
NewNode node=new NewNode(val);
if(head==null){
head=node;
}else {
node.next=head;
head=node;
}size++;
}
public void addIndex(int index,int val){
//在index位置插入值val
if(index<0||index>size){
System.out.println("illegal!!!");
return;
}else {
NewNode node=new NewNode(val);
NewNode temp=head;
for (int i = 0; i < index - 1; i++) {
node.next=temp.next;
temp.next=node;
size++;
}
}
}
private boolean rangeCheck (int index){///改查删时使用的判断,是否合法
if(index<0||index>=size){
return false;
}else {
return true;
}
}
public int get(int index){//查找index位置元素
if(rangeCheck(index)==true){
NewNode temp=head;
for (int i=0;i<index;i++){
temp=temp.next;
}
return temp.val;}
else {
System.out.println("illedgr!!!");
} return -1;
}
public boolean contains(int val){//查是否含有值val
for(NewNode temp=head;temp!=null;temp=temp.next){
if(temp.val==val){
return true;
}
}return false;
}
public int set(int index,int newVal){//改
if(rangeCheck(index)==true){
NewNode node=head;
for (int i = 0; i < index; i++) {
node=node.next;
}
int oldVal=node.val;
node.val=newVal;
return oldVal;
}else {
return -1;
}
}
public String toString(){
String ret=" ";
NewNode prev=head;
while (prev!=null){
ret+= prev.val;
ret+="-->";
prev=prev.next;
}
ret+="NULL";
return ret;
}
}
public class Test2 {
public static void main(String[] args) {
LinkLIST a=new LinkLIST();
a.addFirst(2);
a.addFirst(3);
a.addFirst(1);
a.addFirst(5);
System.out.println(a);
a.addIndex(2,7);
System.out.println(a);
System.out.println(a.get(2));
System.out.println(a.get(9));
System.out.println("-----------------");
System.out.println(a.contains(5));
System.out.println(a.contains(15));
System.out.println(a.set(3,666));
}
}
输出结果:
?
删除操作后续在更新啦?
|