[英]Reversing a Linked List with 2 pointers
我正在嘗試僅使用兩個指針來創建一個鏈表(我查看過的每個帖子似乎都使用3,但是我的分配要求是2)
因此,我將從如何處理此問題開始。 目前,這些值的鏈接方式為nullptr->(head)1-> 2-> ...-> 7-> 8-> nullptr,其中反轉的值為1,2,3,4,5,6, 7,8
void reverseList(){
ListNode *last = head;
ListNode *current = last->next;
if(current == nullptr) return;
while(current != nullptr){
current->next = last;
last = current;
current = last->next;
}
}
從邏輯上講,我的循環在紙上起作用,但是在我的思想和調試器中這是一個無限循環。
我還嘗試制作一個循環來檢查大小並從頭開始,頭= 8,尾= 1,但這也沒有用。
我還嘗試了一種二進制搜索方法,在其中找到了中點,並進行了+-中和交換,但是我也沒有辦法從4-> 3開始。
我的目標是從1-> 2-> 3-> 4-> 5-> 6-> 7-> 8到8-> 7-> 6-> 5-> 4-> 3-> 2 -> 1
使其更簡單,改為移動head
ptr。
由於display()
首先在head
開始。
void reverseList(){
ListNode* current = head->next;
if(current == nullptr) return; // list is empty
head->next = nullptr;
while(current != nullptr) { // have we reached the end of a forward list?
ListNode* next = current->next;
current->next = head; // reverse next pointer to "previous" node
head = current; // move last pointer to "current" node
current = next; // move to "next" node
}
}
首次進入循環時,電流指向“ 2”。 然后發生這種情況:
所以列表現在是(head)1-> 2->(last == head)1-> 2-> 1-> 2-> 1 ...您已創建一個循環。 這就是您的程序永不終止的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.