首页 > 代码库 > 链表(Java版)
链表(Java版)
//链接点类 package com.huowolf.test2; public class Link { private long data; private Link next; public Link(long data) { this.data = http://www.mamicode.com/data;>//链表类 package com.huowolf.test2; public class LinkList { private Link first; //插入结点 public void insert(long value) { Link lnk = new Link(value); if(first == null) { first = lnk; } else { lnk.setNext(first); first = lnk ; } } public void display() { Link current = first; while(current != null) { System.out.print(current.getData() + " "); current = current.getNext(); } } //查找结点 public Link find(long key) { Link current = first; while(current.getData() != key) { if(current.getNext() == null) { return null; } current = current.getNext(); } return current; } //插入结点到指定位置 public void insert(long value,int pos) { if(pos == 0) { insert(value); } else { Link current = first; for(int i = 0; i < pos-1; i++) { current = current.getNext(); } Link lnk = new Link(value); lnk.setNext(current.getNext()); current.setNext(lnk); } } //删除指定结点 public void delete(long key) { Link current = first; Link ago = first; while(current.getData() != key) { if(current.getNext() == null) { return; } else { ago = current; current = current.getNext(); } } if(current == first) { first = first.getNext(); } else { ago.setNext(current.getNext()); } } }//测试类 package com.huowolf.test2; public class TestLinkList { public static void main(String[] args) { LinkList list = new LinkList(); /* int n = 0; Scanner sc = new Scanner(System.in); while(true){ n = sc.nextInt(); if(n == -1) break; list.insert(n); } sc.close(); */ list.insert(40); list.insert(20); list.insert(15); list.insert(30); list.insert(55); list.display(); System.out.println(); System.out.println("找到结点,数据为"+list.find(40).getData()); list.insert(25, 2); list.display(); list.delete(15); System.out.println("-----------------------"); list.display(); } }链表(Java版)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。