简体   繁体   English

某些测试用例未能逆转双向链接列表

[英]Failing certain test cases for reversing a doubly-linked list

My implementation for a doubly linked list is listed down below, but for some reason I am not passing one test case. 下面列出了我的双向链表实现,但是由于某种原因,我没有通过一个测试用例。 The reverse function only gives us the head of a doubly linked list, and does NOT give us the tail. 反向功能仅使我们成为双链表的首部,而没有给我们尾部。 Is there a certain edge case that I could be missing? 是否有某些我可能会想念的边缘情况? ` // Complete the reverse function below. `//完成下面的反向功能。

/*
 * 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;
    }

}

These logics are wrong: 这些逻辑是错误的:

// 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).
  }

Start with head : 开始用head

DoublyLinkedListNode current = head.next;   // <<<< current = head
head.next = null;  // <<<< comment out this line

In while loop : while循环中:

No need to update head each time. 无需每次都更新head Update it with the current at the end of the loop. 在循环结束时使用current对其进行更新。

I've removed the unnecessary and incorrect logic and variables. 我删除了不必要和不正确的逻辑和变量。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM