首页 > 代码库 > 链表(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版)