数据结构链表的实现

public class List {
	
	private Node head;//头指针
	private Node last;//尾指针
	private int size;//链表的有效长度
	
	//结点组成:数据+next指针
	public static class Node{
		int data;//存储数据
		Node next;//指向下一个结点
		Node(int data){
			this.data = data;
		}
	}
	/**
	 * 插入数据
	 * @param index  需插入数据的位置
	 * @param value  数据的值
	 * @throws Exception
	 */
	public void insert(int index,int value) throws Exception {
		if(index>size||index<0) {
			throw new IndexOutOfBoundsException("位置无效!");
		}
		
		//创建插入的节点
		Node insertNode = new Node(value);
		
		if(size == 0){//空链表
			head = insertNode;
			last = insertNode;
		}
		//插入位置在头部
		else if(index==0){
			insertNode.next = head;
			head = insertNode;
		}
		//插入位置在尾部
		else if(index == size) {
			last.next = insertNode;
			last = insertNode ;
		}
		//插入位置在中间
		else {
			Node preNode = get(index-1);
			insertNode.next = preNode.next;
			preNode.next = insertNode;
		}
		size++;//你又忘记了!!
	}
	
	/**
	 * 删除指定位置的数据并返回被删除的数据
	 * @param index 需删除数据的下标
	 */
	public void delete(int index) throws Exception {
		if(index<0||index>size) {
			throw new IndexOutOfBoundsException("位置输入错误");
		}
		
		//删除头节点
		if(index == 0) {
			head = head.next;
		}
		//删除尾节点
		else if(index == size-1) {
			Node preNode = get(index-1);
			preNode =  last;
		}
		//删除中间节点
		else {
			Node preNode = get(index-1);
			preNode.next =  preNode.next.next;
		}
		size--;//你又忘记了!!
		System.out.println(get(index).data);
		
	}
	
	
	//遍历输出链表
	public void show() {
		Node temp = head;
		while(temp!=null) {
			System.out.print(temp.data+"  ");
			temp = temp.next;
		}
		System.out.println();
	}


	/**
	 * 获取指定位置的节点
	 * @param index  取数的下标
	 * @return
	 */
	public Node get(int index) throws Exception{
		// TODO Auto-generated method stub
		//修改:你忘了考虑特殊情况啦!如果链表为空呢?
		if(index<0||index>size) {
			throw new IndexOutOfBoundsException("下标输入不正确");
		}
		Node node = head;
		for(int i=0;i<index;i++) {
			node = node.next;
		}
		return node;
	}


	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		
		List list = new List();
		list.insert(0, 1);
		list.insert(1, 2);
		list.insert(2, 3);
		list.insert(3, 4);
		list.insert(4, 5);
		list.show();
		list.delete(2);
		list.show();
		System.out.println(list.get(1).data);

	}

}

然后今天我发现一个错误“Duplicate modifier for the method get in type List”看了好久,然后才发现多写了一个访问类型hhhhhh

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值