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

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值