Java刷题实现链表问题
是这样的,我在lc上面刷题。写链表题目的时候只能在lc上面提交,因为lc上面有提供ListNode
这就只能在lc上面写题目了,遇到问题调试要开会员,我就想在本地写一个ListNode,然后写题目这样还能调试代码。这是我写的ListNode
public class ListNode {
public int value;
public ListNode next;
public ListNode(int value) {
this.value = value;
}
public ListNode(int value, ListNode next) {
this.value = value;
this.next = next;
}
public ListNode head;
public ListNode() {
this.head = null;
}
// 添加节点
public void append(int value) {
ListNode newNode = new ListNode(value);
if (head == null) {
head = newNode;
return;
}
ListNode last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
// 打印遍历
public void printList() {
ListNode current = head;
while (current != null) {
System.out.print(current.value + " ");
current = current.next;
}
System.out.println();
}
试过了添加和打印遍历都是没有问题的,但是用来写题目遍历出来的都不是正确答案,但是在lc上面还是正确提交的比如这道
合并两个有序链表
private static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
if (list1.value < list2.value) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
main方法
public static void main(String[] args) {
ListNode list1 = new ListNode();
list1.append(1);
list1.append(2);
list1.append(4);
System.out.print("list1: "); list1.printList();
ListNode list2 = new ListNode();
list2.append(1);
list2.append(3);
list2.append(4);
System.out.print("list2: "); list2.printList();
System.out.println("=======================");
mergeTwoLists(list1, list2).printList();
}
输出结果
个人推测可能是ListNode有啥问题,希望各位可以指点