链表这种数据结构,各对象按照线性顺序进行排列,每一个对象包含一个关键字域以及两个指针next和PRev
下面是链表的示意图:
下面再来看一下链表的删除以及插入操作(删除插入是链表擅长的,效率要比数组高很多)
2.插入
3.删除
最后贴出实现链表的代码:
package aa;public class MyList { Node head=null; class Node{ Node next=null; Object data; public Node(Object data){ this.data=data; } } //返回链表的长度 public int length(){ int length=0; Node pointer=head; while(pointer!=null){ length++; pointer=pointer.next; } return length; } //插入节点 public void insert(Object data){ Node nodew=new Node(data); if(head==null){ head=nodew; return; } Node pointer=head;//指向head while(pointer.next!=null){ pointer=pointer.next; } pointer.next=nodew; } //删除节点 public boolean delete(int index){ if(index<1||index>length()){ return false; } if(index==1){//如果删除的是头节点,那么直接将头节点指向下一个节点 head=head.next; return true; } int i=1; Node preNode=head; Node curNode=preNode.next; while(curNode!=null){ if(i==index){// preNode.next=curNode.next; return true; } preNode=curNode; curNode=curNode.next; i++; } return false; } //打印链表 public void printList(){ Node pointer=head; while(pointer!=null){ System.out.println(pointer.data); pointer=pointer.next; } } public static void main(String[] args){ MyList mylist=new MyList(); mylist.insert(1); mylist.insert(2); mylist.insert(3); mylist.insert("pg"); mylist.insert("sg"); mylist.insert("pf"); mylist.insert("pg"); mylist.insert("C"); System.out.println(mylist.length()); mylist.delete(2); mylist.printList(); }}
新闻热点
疑难解答