双向链表的实现

package com.gyq.Test;

/**  
* 类说明  :双向链表的实现
*  描述:TODO
* @author 郭莹棋
* @date 2018年11月23日
*/

public class myLinked {
  //第一个节点
    private Node first;
  //最后一个节点
    private Node last;
  //链表长度
    int size;

class Node{
   Node previous;
    Object object;
    Node next;
    

 public Node() {
        
    }
    public Node(Node previous, Object object, Node next) {
        super();
        this.previous = previous;
        this.object = object;
        this.next = next;
    }
   }

  
  //添加一个元素
 public void add(Object object) {
     Node node = new Node();
     if(first == null) {
        node.previous = null;
        node.object = object;
        node.next = null;
        
        first = node;
        last = node;
     }else {
         node.previous = last;
         node.object= object;
         node.next = null;
         
         last.next= node;
         last = node;
     }
 size++;
 }
 //检查下标是否正常
 public void rangeCheck(int index) {
     if(index < 0 || index >= size) {
         try{
             throw new Exception();
         } catch(Exception e) {
             e.printStackTrace();
         }
     }
 }
 
 //得到链表长度
 public int getSize() {
     return size;
 }
  
 //得到指定下标的节点
 public Node node(int index) {
     Node temp = null;
     if(first != null) {
         temp = first;
         for(int i = 0;i < index;i++) {
             temp = temp.next;
             return temp;
         }
     }
     return null;
 }
 
 //得到指定下标节点的值
 public Object get(int index) {
    Node temp = node(index);
    if(temp != null) {
         return temp.object;
    }
return null;
 }
  
 //移除指定下标的节点
 public void remove(int index) {
     Node temp = node(index);
     if(temp != null) {
         Node up = temp.previous;
         Node down = temp.next;
         
         up.next = down;
         down.previous = up;
     }
 }
 
 //在指定位置添加一个节点
 public void add(int index,Object object) {
     Node temp = node(index);
     Node n = new Node();
     n.object = object;
     
     if(temp != null) {
         Node up = temp.previous;
         up.next = n;
         n.previous = up;
         
         n.next = temp;
         temp.previous = n;
         
     }
 }
 
 public static void main(String[] args) {
     myLinked t = new myLinked();
     t.add("rch");
     t.add("gyq");
     t.add("shibi");
     //t.remove(1);
     System.out.println(t.get(1));
     //t.add(1, "sddd");
      //System.out.println(t.get(1));
}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值