如何用Java构造链表

节点定义

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
    // 递归打印链表
    public void print(){
        System.out.print(this.val);
        if(this.next != null){
            System.out.print("->");
            this.next.print();
        }
    }
}

数组内容构造链表

public class CreateListNode {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        ListNode dummy = new ListNode(-1); //虚拟头结点
        ListNode r, s;
        r = dummy; // 定义尾结点,尾节点动,原链表不动
        for (int i : a) {
            s = new ListNode(i);
            r.next = s;
            r = r.next;
        }
        r.next = null;
        dummy.print(); //-1->1->2->3->4->5
        dummy.next.print(); //1->2->3->4->5
    }
}

构造环形链表

在这里插入图片描述

public static void main(String[] args) {
    int[] a = {3, 2, 0, 4};
    ListNode dummy = new ListNode(-1); //虚拟头结点
    ListNode r, s, p = null;
    r = dummy; // 定义尾结点,尾节点动,原链表不动
    for (int i : a) {
        s = new ListNode(i);
        r.next = s;
        r = r.next;
        if(i==2){ //留下2号节点
            p = r;
        }
    }
    r.next = p;    
    
    // 检测环第一个节点
    ListNode res = detectCycle(dummy.next);
    if (res != null)
        System.out.println(res.val);

    // 打印环形链表
    ListNode head = dummy.next;
    r = head;
    // 这里不能直接全部打印,因为环形链表是一个死循环
    for (int i = 0; i < 6; i++) {
        System.out.println(r.val);
        r = r.next;
    } //3,2,0,4, 2, 0
}

节点中定义add()方法

1. 单链表节点定义

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }

    // 递归方式添加结点(尾插)
    public void add(int x){
        ListNode node = new ListNode(x);
        if(this.next == null){
            this.next = node;
        }else {
            this.next.add(x);
        }
    }

    // 递归打印链表
    public void print(){
        System.out.print(this.val);
        if(this.next != null){
            System.out.print("->");
            this.next.print();
        }
    }
}

2. 创建一个单链表

/*1.一个个添加节点 */
int[] input = {1, 2, 3, 4, 5};
ListNode head = null;
for (int i = 0; i < input.length; i++) {
    if (head == null) {
        head = new ListNode(input[i]);
    } else {
        head.add(input[i]);
    }
}
head.print(); // 1->2->3->4->5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值