某些用于反转双向链表的测试用例失败
Failing certain test cases for reversing a doubly-linked list
下面列出了我对双向链表的实现,但出于某种原因我没有通过一个测试用例。 reverse 函数只给我们一个双向链表的头部,并没有给我们尾部。是否存在某些我可能会遗漏的极端情况?
`
// 完成下面的反向函数。
/*
* For your reference:
*
* DoublyLinkedListNode {
* int data;
* DoublyLinkedListNode next;
* DoublyLinkedListNode prev;
* }
*
*/
static DoublyLinkedListNode reverse(DoublyLinkedListNode head) {
// If the linked list is empty, return null
if (head == null) {
return null;
}
// If the linked list has only one element, return head becaue reverse of one ele is itself
else if (head.next == null) {
return null;
}
// Otherwise reverse
else {
DoublyLinkedListNode current = head.next;
head.next = null;
while (current != null) {
DoublyLinkedListNode nextCurr = current.next;
DoublyLinkedListNode prevCurr = current.prev;
current.next = prevCurr;
current.prev = nextCurr;
head = current;
current = nextCurr;
}
return head;
}
}
这些逻辑是错误的:
// If the linked list has only one element, return head becaue reverse of one elem is itself
else if (head.next == null) {
return null; //return head instead (unchanged).
}
从 head
开始:
DoublyLinkedListNode current = head.next; // <<<< current = head
head.next = null; // <<<< comment out this line
在while
循环中:
不需要每次都更新head
。在循环结束时用 current
更新它。
我删除了不必要和不正确的逻辑和变量。
public static DoublyLinkedListNode reverse(DoublyLinkedListNode head) {
while (head != null) {
DoublyLinkedListNode nextCurr = head.next;
head.next = head.prev;
head.prev = nextCurr;
if (nextCurr == null) {
break;
}
head = nextCurr;
}
return head;
}
下面列出了我对双向链表的实现,但出于某种原因我没有通过一个测试用例。 reverse 函数只给我们一个双向链表的头部,并没有给我们尾部。是否存在某些我可能会遗漏的极端情况? ` // 完成下面的反向函数。
/*
* For your reference:
*
* DoublyLinkedListNode {
* int data;
* DoublyLinkedListNode next;
* DoublyLinkedListNode prev;
* }
*
*/
static DoublyLinkedListNode reverse(DoublyLinkedListNode head) {
// If the linked list is empty, return null
if (head == null) {
return null;
}
// If the linked list has only one element, return head becaue reverse of one ele is itself
else if (head.next == null) {
return null;
}
// Otherwise reverse
else {
DoublyLinkedListNode current = head.next;
head.next = null;
while (current != null) {
DoublyLinkedListNode nextCurr = current.next;
DoublyLinkedListNode prevCurr = current.prev;
current.next = prevCurr;
current.prev = nextCurr;
head = current;
current = nextCurr;
}
return head;
}
}
这些逻辑是错误的:
// If the linked list has only one element, return head becaue reverse of one elem is itself
else if (head.next == null) {
return null; //return head instead (unchanged).
}
从 head
开始:
DoublyLinkedListNode current = head.next; // <<<< current = head
head.next = null; // <<<< comment out this line
在while
循环中:
不需要每次都更新head
。在循环结束时用 current
更新它。
我删除了不必要和不正确的逻辑和变量。
public static DoublyLinkedListNode reverse(DoublyLinkedListNode head) {
while (head != null) {
DoublyLinkedListNode nextCurr = head.next;
head.next = head.prev;
head.prev = nextCurr;
if (nextCurr == null) {
break;
}
head = nextCurr;
}
return head;
}