如何在Java单链表中实现指向指定节点的Cursor?
替代方案:通过嵌套Cursor类+链表定位方法实现
我给你一套完整的修改方案,既能满足Cursor关联指定节点的需求,又能保证链表的封装性不被破坏:
修改后的完整代码
public class SinglyLinkedList { //---------------- nested Node class ---------------- private static class Node { private String element; private Node next; public Node(String e, Node n) { element = e; next = n;} public String getElement() { return element; } public Node getNext() { return next; } public void setNext(Node n) { next = n; } } //---------------- 新增嵌套Cursor类 ---------------- public static class Cursor { private Node currentNode; // 私有构造方法,只能由SinglyLinkedList内部创建 private Cursor(Node node) { this.currentNode = node; } // 给外部提供Cursor的基础操作方法 public String getCurrentElement() { return currentNode != null ? currentNode.getElement() : null; } public void moveToNext() { if (currentNode != null) { currentNode = currentNode.getNext(); } } public boolean hasNext() { return currentNode != null && currentNode.getNext() != null; } } private Node head = null; private Node tail = null; private int size = 0; public SinglyLinkedList() { } // access methods public int size() { return size; } public boolean isEmpty() { return size == 0; } public String first() { if (isEmpty()) return null; return head.getElement(); } public String last() { if (isEmpty()) return null; return tail.getElement(); } // update methods public void addFirst(String e) { head = new Node(e, head); if (size == 0) tail = head; size++; } public void addLast(String e) { Node newest = new Node(e, null); if (isEmpty()) head = newest; else tail.setNext(newest); tail = newest; size++; } // 新增方法:获取指定位置的Cursor(位置从1开始计数) public Cursor getCursorAtPosition(int position) { if (position < 1 || position > size) { throw new IllegalArgumentException("Invalid position: " + position); } Node current = head; // 遍历到目标位置的节点 for (int i = 1; i < position; i++) { current = current.getNext(); } return new Cursor(current); } } class Main { public static void main(String[] args) { SinglyLinkedList liste1 = new SinglyLinkedList(); // 先添加足够多的节点,确保第3、5个节点存在 liste1.addLast("Node1"); liste1.addLast("Node2"); liste1.addLast("Node3"); liste1.addLast("Node4"); liste1.addLast("Node5"); liste1.addLast("Node6"); try { // 创建指向第3个节点的C1 SinglyLinkedList.Cursor c1 = liste1.getCursorAtPosition(3); System.out.println("C1当前元素: " + c1.getCurrentElement()); // 输出Node3 // 创建指向第5个节点的C2 SinglyLinkedList.Cursor c2 = liste1.getCursorAtPosition(5); System.out.println("C2当前元素: " + c2.getCurrentElement()); // 输出Node5 // 测试Cursor移动功能 c1.moveToNext(); System.out.println("C1移动后元素: " + c1.getCurrentElement()); // 输出Node4 } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } }
方案核心要点
- 封装性保障:把
Cursor作为SinglyLinkedList的公共静态嵌套类,既让它能访问私有Node,又限制外部直接操作Node;同时Cursor的构造方法设为私有,只能通过链表提供的getCursorAtPosition方法创建,避免外部破坏链表结构。 - 合法性校验:
getCursorAtPosition方法会先检查传入的位置是否在有效范围内,防止越界访问。 - 可扩展性:
Cursor类里提供了getCurrentElement、moveToNext等基础方法,你可以根据需求继续扩展更多操作(比如插入、删除当前节点关联的元素等)。
内容的提问来源于stack exchange,提问作者thetha
相关产品推荐
相关产品推荐

