您的位置:首页 > 编程语言 > Java开发

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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: