java链表的例子

    xiaoxiao2021-12-14  48

    package 链表; class Node { public Node next; public int data; public Node(int data){ this.data=data; this.next=null; } } public class LinkList { public Node head; public LinkList(){ head=null; } //插入节点元素 public void insertNode(int data){ Node newNode=new Node(data); if(head==null) { head=newNode; return; } else{ Node current=head; while(true){ if(current.next==null) { current.next=newNode; return; } current=current.next; } } } // 删除节点元素 public Boolean deleteNode(int index) { if(index<1||index>length()) { return false; } if(index==1){ head=head.next; return true; } int i=2; Node Pre=head; Node Cur=Pre.next; while(Cur!=null) { if(i==index) { Pre.next=Cur.next; return true; } Pre=Cur; Cur=Cur.next; i++; } return true; } //遍历 public void disPlay() { Node list=head; while(list.next!=null) { System.out.print(list.data); list=list.next; } } public int length() { int length=0; Node l=head; while(l.next!=null) { length++; l=l.next; } return length; } public static void main(String[] args) { LinkList list=new LinkList(); list.insertNode(1); list.insertNode(2); list.insertNode(3); list.insertNode(4); list.insertNode(5); System.out.println("lisLen="+list.length()); System.out.println("链表显示:"); list.disPlay(); System.out.println(); list.deleteNode(2); list.disPlay(); } }

    输出结果:

    lisLen=4 链表显示: 1234 134

    转载请注明原文地址: https://ju.6miu.com/read-971811.html

    最新回复(0)