在java中实现泛型链表,通常会定义两个核心类:listnode
ListNode
class ListNode{ private final E val; // 使用final提高不变性 private ListNode next; public ListNode(E val, ListNode next){ this.val = val; this.next = next; } public E getVal(){ return val; } public ListNode getNext(){ return next; } public boolean hasNext() { // 添加辅助方法 return next != null; } public void updateNext(ListNode node){ next = node; } }
LList2
class LList2{ private ListNode front; private ListNode rear; public LList2(ListNode front, ListNode rear){ this.front = front; this.rear = rear; } // ... 其他方法 }
LList2
public void addLast(E obj)
这个签名明确指出,addLast 方法期望接收一个类型为E的参数obj。这意味着它需要的是要添加到链表中的“值”,而不是一个已经封装好的ListNode
public void addLast(E obj){
if(rear != null) {
// 如果链表不为空,则在当前尾节点后添加新节点
rear.updateNext(new ListNode(obj, null));
rear = rear.getNext(); // 更新rear指向新添加的节点
} else {
// 如果链表为空,新节点既是头节点也是尾节点
rear = new ListNode(obj, null);
front = rear;
}
} 注意事项: 在原始代码中,addLast方法在rear != null分支中更新了rear.updateNext,但没有更新rear本身。这意味着rear始终指向旧的尾节点,这会导致后续的addLast操作行为异常。正确的做法是在添加新节点后,将rear更新为新添加的节点。
考虑以下在 main 方法中调用 addLast 的代码片段:
public class SingleLinkedListWorkSheetQ2Q3{
public static void main (String[] args){
// ... 链表初始化代码
LList2 temp = new LList2 <> (list, rear);
// 错误发生在这里
temp.addLast(new ListNode (-2, null));
}
} 当 LList2 被实例化为 LList2
然而,在调用 temp.addLast(new ListNode
这个错误的核心在于混淆了“节点的值”和“节点本身”。addLast 方法期望的是要存储的“值”(例如 -2),而不是一个包含这个值的“节点对象”。
要解决这个类型不兼容错误,只需按照 addLast 方法的预期,传入要添加的实际值即可。方法内部会负责创建新的 ListNode。
public class SingleLinkedListWorkSheetQ2Q3 {
public static void main(String[] args) {
// 初始化链表,示例中为了清晰起见,我们将初始链表构建得更简单
ListNode initialRear = new ListNode<>(0, null);
ListNode listHead = new ListNode<>(3, new ListNode<>(2, new ListNode<>(1, initialRear)));
LList2 temp = new LList2<>(listHead, initialRear);
System.out.print("初始链表: ");
temp.printWhile(); // 打印 [3,2,1,0]
// 正确的调用方式:直接传入值 -2
temp.addLast(-2);
System.out.print("添加-2后: ");
temp.printWhile(); // 打印 [3,2,1,0,-2]
// 再次添加一个值
temp.addLast(99);
System.out.print("添加99后: ");
temp.printWhile(); // 打印 [3,2,1,0,-2,99]
}
} 为了更好地展示链表内容,可以优化 printWhile 方法的输出格式,使其更符合常见的链表表示方式,并避免在最后一个元素后出现逗号。
class LList2{ // ... 构造器及其他方法 public void printWhile() { StringBuilder sb = new StringBuilder("["); ListNode current = front; // 使用局部变量遍历,不改变front while (current != null) { sb.append(current.getVal()); if (current.hasNext()) { // 只有当有下一个节点时才添加逗号 sb.append(", "); } current = current.getNext(); } sb.append("]"); System.out.println(sb.toString()); } // printFor 也可以类似优化 public void printFor() { StringBuilder sb = new StringBuilder("["); for (ListNode temp = front; temp != null; temp = temp.getNext()) { sb.append(temp.getVal()); if (temp.hasNext()) { sb.append(", "); } } sb.append("]"); System.out.println(sb.toString()); } // ... addFirst, addLast 方法 }
注意: 在原始的printWhile方法中,它直接修改了front引用,导致链表在打印后被“清空”(front变为null)。为了避免这种副作用,应该使用一个局部变量(如current)来遍历链表。
本教程通过分析一个常见的Java泛型链表类型不兼容错误,强调了以下关键点:
遵循这些原则,可以更有效地使用Java泛型构建健壮且易于理解的数据结构。