java双链表

 As is known to all,自jdk1.7后LinkedList取消了循环,改为双链表

//定义结点类
class Node {
    public int val;
    public Node prev, next;

    public Node(int val) {
        this.val = val;
        this.prev = null;
        this.next = null;
    }
}
/*
*无头结点写双链表
*/
class LinkList {
    public int size;//记录插入结点的数量
    public Node head, tail;//定义头,尾指针

    //尾插法添加结点
    public void append(int val) {
        Node node = new Node(val);
        if (this.head == null) {
            this.head = this.tail =  node;
            size++;
        } else {
            this.tail.next = node;
            node.prev = tail;
            tail = node;
            size++;
        }
    }
    //插入方法
    public void insert(int index, int val){
        //判断链表是否为空,index是否大于size
        if (this.head == null || index > size || index <= 0) {
            return;
        }
        Node cur = this.head;
        Node node = new Node(val);
        //找到第index个节点
        for (int i = 1; i < index; i++) {
            cur = cur.next;
        }
        if (index == 1) {
            //因为没有头结点,把结点插入到第一个结点不方便,所以单独拎出来操作
            //将新增结点插入到第1和第2个结点中间
            node.next = cur.next;
            node.prev = cur;
            cur.next.prev = node;
            cur.next = node;
            //把首尾结点的值交换
            cur.val += cur.next.val;
            cur.next.val = cur.val - cur.next.val;
            cur.val -= cur.next.val;
            size++;
            return;
        }
        //正常插入结点操作
        // 先连接,再断链
        node.next = cur;
        cur.prev.next = node;
        node.prev = cur.prev;
        cur.prev = node;
        size++;
    }

    //正序打印方法
    public void display(){
        Node cur = this.head;
        while (cur != null){
            System.out.println(cur.val);
            cur = cur.next;
        }
    }

    //逆序打印方法
    //这个方法也是为了判断咱们的双链有没有连接成功
    public void displayInverse(){
        Node cur = this.tail;
        while (cur != null){
            System.out.println(cur.val);
            cur = cur.prev;
        }
    }
}
public class MyLinkList {
    public static void main(String[] args) {
        //测试代码
        LinkList list = new LinkList();
        list.append(1);
        list.append(3);
        list.append(5);
        list.append(7);
        list.insert(4,99);
        list.display();
        System.out.println("-------");
        list.displayInverse();
        System.out.println("结点个数" + list.size);
    }
}

以上是我用java写双链表的练习,没有用头结点,因为俺不喜欢

写的不好的地方欢迎指点

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值