我目前正在练习指针在我的学校休息时间和下面我写的方法来扭转双向链表,但是当我把它交给在线测试时,它会失败。扭转双尾列表从尾到头
Node* Reverse(Node *head)
{
int count = 0;
struct Node *ptr = head;
// return head if NULL
if (head == NULL) {
return head;
}
// if the list is only the head, then the reverse is just the head... so nothing changes
if((head->next == NULL && head->prev == NULL)){
return head;
}
//Come here if previous if statements fail, traverse the list until I reach tail which will become the
// new head
while(ptr->next != NULL){
ptr = ptr->next;
count++;
}
head = ptr; // this is the new head
//starting from tail all the way to head swap the "prev" and "next" of each node
struct Node *temp = ptr->next;
for(int i = 0; i<count; i++){
ptr->next = ptr->prev;
ptr->prev = temp;
ptr=ptr->next;
temp= ptr->next;
//count--;
}
return head;
}
我意识到,这可能是聪明扭转名单,而我从头部到尾部遍历它,但我认为这是无聊,所以我决定改变它从尾部开始,而不是头部。我怀疑我的while循环或循环中有明显的错误,但我无法诊断错误。
在线测试给出了什么错误? – nobism
'Node Node' - >'Node'或'Node * head' - >'Node Node * head' – BLUEPIXY
这里是错误:错误的答案! 一些可能的错误: 1.您从该函数返回了NULL值。 2.您的逻辑存在问题 – Belphegor