码迷,mamicode.com
首页 > 编程语言 > 详细

链表(Java版)

时间:2015-02-01 09:37:52      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:链表      java   数据结构   测试   

//链接点类
package com.huowolf.test2;

public class Link {
		private long data;
		private Link next;
		
		public Link(long data) {
			this.data  = data;
		}

		public long getData() {
			return data;
		}

		public void setData(long data) {
			this.data = data;
		}

		public Link getNext() {
			return next;
		}

		public void setNext(Link next) {
			this.next = next;
		}
		
		
}

//链表类
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版)

标签:链表      java   数据结构   测试   

原文地址:http://blog.csdn.net/huolang_vip/article/details/43352275

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!