java单链表
2016-08-08 10:55
316 查看
单链表操作:
在链表头插入一个数据项
在链表头删除一个数据项
遍历链表显示他的内容
在链表头插入一个数据项
在链表头删除一个数据项
遍历链表显示他的内容
public class Link { public int iData; //data item key public double dData;//date item public Link next; public Link(int id,double dd){ iData = id; dData = dd; } public void displayLink(){ System.out.print("{" + iData + "," + dData + "} "); } }
public class LinkList { private Link first; public LinkList(){ first = null; } public boolean isEmpty(){ return first == null; } public void insertFirst(int id,double dd){ Link newLink = new Link(id,dd); newLink.next = first;//newLink-->old link first = newLink;//first-->newLink } public Link deleteFirst(){ Link temp = first; first =first.next;//first-->old next return temp; } public void displayList(){ System.out.print("Link(first-->last):"); Link current = first; while(current!=null){ current.displayLink(); current=current.next; } System.out.println(""); } public Link find(int key){ Link current = first; while(current.iData!=key){ if(current.next==null){ return null; }else{ current=current.next; } } return current; } public Link delete(int key){ Link current = first; Link previous = first; while(current.iData!=key){ if(current.next==null) return null; else{ previous=current; current=current.next; } } if(current==first){ first=first.next; }else{ previous.next=current.next; } return current; } }
public class LinkListApp { public static void main(String[] args) { LinkList list = new LinkList(); list.insertFirst(1, 11.22); list.insertFirst(2, 34.22); list.insertFirst(3, 25.56); list.insertFirst(4, 241.234); list.displayList(); while(!list.isEmpty()){ Link aList = list.deleteFirst(); System.out.print("deleted:"); list.displayList(); System.out.println(""); } list.displayList(); list.insertFirst(1, 11.22); list.insertFirst(2, 34.22); list.insertFirst(3, 25.56); list.insertFirst(4, 241.234); list.displayList(); Link f = list.find(3); if(f!=null){ System.out.println("found link with key:"+f.iData); }else{ System.out.println("can't find link"); } Link d = list.delete(2); if(d!=null){ System.out.println("deleted link with key:"+d.iData); }else{ System.out.println("can't delete link"); } list.displayList(); } }
相关文章推荐
- Java单链表反转
- Java单链表基本操作(七)--排序
- Java中单链表的实现和单链表的反转(倒置)
- Java单链表基本操作(十)--判断单链表是否有环并输出环长度以及环的入口节点
- Java之单链表
- 【java数据结构】单链表实现
- java实现单链表的整表创建
- java实现单链表的基本操作
- 数据结构与算法(Java描述)-4、单链表以及单链表的应用
- Java判断单链表是否有环的两种实现方法
- java单链表的实现
- 面试之路(10)-BAT面试之java实现单链表的插入和删除
- 通过Java实现单链表来透彻理解抽象数据类型的定义和应用
- Java单链表的实现
- Java模拟单链表和双端链表数据结构的实例讲解
- 删除单链表中重复的值(Java版)
- JAVA单链表的实现-不带头结点且没有尾指针
- 数据结构与算法Java版——单链表的实现
- 单链表(java语言实现)
- java实现单链表