我嘗試使用以下代碼反轉鏈表,但列印中僅顯示未反轉鏈表的第一個元素。
請幫忙。
輸出是:
Element: 7
Element: 11
Element: 66
------------------
Element: 7
破折號之前的元素是不反轉的,下面的元素是反轉的,沒有發生。
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
void LinkedListTraversal(struct Node *ptr)
{
while (ptr != NULL)
{
printf("Element: %d\n", ptr->data);
ptr = ptr->next;
}
}
struct Node *Reverse(struct Node *head)
{
Node *cur = head;
Node *prev = NULL;
Node *temp;
// temp;
while (cur != NULL)
{
/* code */
temp = cur->next;
cur->next = prev;
prev= cur;
// cout<<prev->next<<endl;
cur = temp;
}
head = prev;
return head;
}
int main()
{
// Creation of Linked List
struct Node *head;
struct Node *second;
struct Node *third;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
head->data = 7;
head->next = second;
second->data = 11;
second->next = third;
third->data = 66;
third->next = NULL;
LinkedListTraversal(head);
Reverse(head);
cout << "------------------\n";
LinkedListTraversal(head);
return 0;
}
uj5u.com熱心網友回復:
您的Reverse功能運行良好。
你會笑,因為你的錯誤真的很愚蠢:你為你的函式使用了錯誤的引數。現在您的串列已反轉,head是新的尾部,它指向NULL.
像這樣呼叫你的函式:
LinkedListTraversal(head);
Reverse(head);
cout << "------------------\n";
LinkedListTraversal(third);
uj5u.com熱心網友回復:
讓我們看一個簡單的例子 A->B->NULL:
Node *cur = head; // cur = &A
Node *prev = NULL;
Node *temp;
// temp;
while (cur != NULL)
{
/* code */
temp = cur->next; // temp = &B
cur->next = prev; // A.next = NULLL
prev= cur; // prev = &A
// cout<<prev->next<<endl;
cur = temp; // cur = &B
} // ends because B.next == NULL
head = prev; // head = &A, with A.next still NULL
return head;
您最終以 A->NULL 作為反向串列。
當然,它只會導致“A”的輸出。
uj5u.com熱心網友回復:
你有一個類似7 -> 11 -> 66wherehead指向的串列7。然后將串列反轉為66 -> 11 -> 7. 新的head應該指向66。您的代碼從未修改的串列中列印出head仍然指向7.
您的函式Reverse旨在回傳新的串列頭,但您忽略了回傳值。采用
head = Reverse(head);
在您的main功能中獲得新的頭。
也許您認為這會Reverse修改head. main這不是真的。該函式僅修改指標的本地副本。這就是它回傳新值的原因。如果您要設計Reverse獲取head指標的地址,它可以修改main.
替代解決方案:
/* modified lines marked with comments ***** */
struct Node *Reverse(struct Node **head)
{
Node *cur = *head; /*****/
Node *prev = NULL;
Node *temp;
// temp;
while (cur != NULL)
{
/* code */
temp = cur->next;
cur->next = prev;
prev= cur;
// cout<<prev->next<<endl;
cur = temp;
}
*head = prev; /*****/
}
/* and to pass the address of the head pointer, call it like */
Reverse(&head);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457389.html
標籤:C
