1 class Node{ 2 int data; 3 Node next; 4 Node(int data){ 5 this.data=data; 6 } 7 } 8 public class MyNodes { 9 private Node head; 10 private Node last; 11 private int size; 12 public Node get(int index){ 13 if(index<0 || index>=size){ 14 return null; 15 } 16 Node temp=head; 17 for (int i=0;i<index ; i++){ 18 temp=temp.next; 19 } 20 return temp; 21 } 22 public void insert(int data,int index) throws Exception{ 23 if(index<0 || index>size){ 24 throw new IndexOutOfBoundsException("超出链表节点范围"); 25 } 26 Node insertNode=new Node(data); 27 if(size==0){ 28 head=insertNode; 29 last=insertNode; 30 }else if(index==0){ 31 //头部插入 32 insertNode.next=head; 33 head=insertNode; 34 }else if(index==size){ 35 //尾部插入 36 last.next=insertNode; 37 last=insertNode; 38 }else{ 39 //中间插入 40 Node prevNode=get(index-1); 41 Node nextNode=get(index); 42 prevNode.next=insertNode; 43 insertNode.next=nextNode; 44 } 45 size++; 46 } 47 public void remove(int index)throws Exception{ 48 if(index<0 || index>size)throw new Exception("超出范围"); 49 if(index==0){ 50 //删除首元素 51 head=head.next; 52 }else if(index==size-1){ 53 Node temp =get(index-1); 54 last=temp; 55 last.next=null; 56 temp.next=null; 57 }else{ 58 //删除中间元素 59 Node Pre_temp=get(index-1); 60 Node Last_temp=get(index+1); 61 Pre_temp.next=Last_temp; 62 } 63 size--; 64 } 65 public void output(){ 66 Node temp=head; 67 while (temp !=null){ 68 System.out.println(temp.data); 69 temp=temp.next; 70 } 71 } 72 73 }View Code
标签:Node,index,head,temp,实现,next,链表,insertNode,双向 From: https://www.cnblogs.com/dmfsmile/p/18094942