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

时间:2018-10-10 17:35:04

标签: java doubly-linked-list

下面列出了我对双向链接列表的实现,但是由于某种原因,我没有通过一个测试用例。反向功能仅使我们成为双链表的首部,而没有给我们尾部。是否有某些我可能会想念的边缘情况? `     //完成下面的反向功能。

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

}

2 个答案:

答案 0 :(得分:0)

这些逻辑是错误的:

// 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更新它。

答案 1 :(得分:0)

我删除了不必要和不正确的逻辑和变量。

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