#include <iostream>
使用 命名空間 std.com.cn>。
class Node{
public:
int data;
Node* next;
Node(int val){
data=val;
next=NULL。
}
};
class LinkedList{
public:
節點*頭。
LinkedList(){
head=NULL。
}
void insertAtEnd(intval){
Node *newnode = new Node(val)。
if(head==NULL){
head=newnode。
return;
}
Node *temp=head。
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=newnode。
}
void insertAtHead(int val){
Node *newnode = new Node(val)。
newnode->next=head。
head=newnode。
}
void deleteAtEnd(){
if(head==NULL){
cout<<"List Is Empty"。
return;
}
if(head->next==NULL){
delete head。
return;
}
Node *temp=head。
while(temp->next->next!=NULL){
temp=temp->next;
}
節點 *todel=temp->next。
delete todel;
temp->next=NULL。
}
void print()>{
Node *temp=head。
while(temp! =NULL){
cout<<temp->data<<"->"/span>。
temp=temp->接下來。
}
cout<<"NULL"/span>。
}
};
int main()
{
LinkedList ll;
ll.insertAtEnd(10)。
ll.insertAtEnd(20)。
ll.insertAtEnd(30)。
ll.insertAtEnd(40)。
ll.insertAtEnd(50)。
ll.print()。
cout<<endl;
ll.insertAtHead(100)。
ll.print()。
cout<<endl;
ll.deleteAtEnd()。
ll.deleteAtEnd()。
ll.deleteAtEnd()。
ll.deleteAtEnd()。
ll.deleteAtEnd()。
ll.deleteAtEnd()。
ll.print()。
return 0;
這是我用c 撰寫的linkedlist的代碼。我在deleteAtEnd方法中遇到了一個問題,在洗掉最后一個節點后,它顯示了一些垃圾值。我已經在deleteAtEnd方法中加入了所有的檢查,如果頭部節點被留下,那么就洗掉頭部節點。我找不到我的錯誤,請幫助我解決。如果你能給我提供代碼解決方案,那將對我有好處。這樣,我應該在我的代碼中改變什么代碼,使C程式完美運行。
uj5u.com熱心網友回復:
函式的這一部分deleteAtEnd
if(head->next==NULL){
delete head。
return;
}
是不正確的。
在if陳述句中,你必須將指標head設定為nullptr(或NULL)
if(head-> next==NULL){
delete head;
head = nullptr;
return;
}
如果該函式會使用一個指標,那么它的分支會更少。比如說
bool deleteAtEnd()
{
bool success = head != nullptr;
if ( success )
{
Node **current = &head;
while ( ( *current )->next ) current = &( *current )->next;
delete *current;
*current = nullptr;
}
return success;
}
請注意,該函式不應發出任何資訊。是由函式的使用者根據函式的回傳值來決定是否發出訊息。
另外,函式print應該是一個常量成員函式,因為它不會改變它所呼叫的物件。
void print() const{
const Node *temp=head;
while(temp!=NULL){
cout<<temp->data<<"->"/span>。
temp=temp->接下來。
}
cout<<"NULL"/span>。
}
uj5u.com熱心網友回復:
在你的代碼的deleteAtEnd()函式中,對于鏈接串列中只剩下一個元素的情況,該函式觸發:
if(head->next==NULL){
delete head。
return;
}
注意,雖然它洗掉了鏈接串列中存在的最后一個節點,但指標head仍然指向那個記憶體地址,現在它包含垃圾值。因此,在洗掉最后一個節點后,使head=NULL。
修改后的代碼:
if(head->next==NULL){
delete head;
head = NULL;
return;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310698.html
標籤:
