数据结构-链表实现--待更新

实体类:ListNode

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

}

 链表实现:插入和打印 LinkedList 

public class LinkedList {
    ListNode head;

//     插入节点到链表尾部
    public void insert(int val) {
        ListNode newNode = new ListNode(val);

        if (head == null) {
            // 如果链表为空,新节点成为头节点
            head = newNode;
        } else {
            // 否则,遍历到链表尾部并插入新节点
            ListNode current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

//     打印链表
    public void printList() {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }

}

测试类:

public class LibraryTest extends TestCase {

    @Test
    public void testAddNode() {

        LinkedList linkedList = new LinkedList();
        linkedList.insert(2);
        linkedList.insert(1);
        linkedList.printList();

    }
}

问题:

传入参数1时

此时的head结构是[2,null]

current.next=newNode更新后,为什么head也更新了?

从代码:ListNode current = head;

这代表着current和head指向同一对象,current发生改变,head也更新

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值