我輸入了 1234,但串列中有 4,3,2,1。我懷疑問題出在 getchar() 本身,或者是類中的一個函式,但我無法找出答案。鏈接
類負責一些鏈表操作,如洗掉、插入等,而節點類則負責創建和分配節點。
createlist類負責創建鏈表,這是問題的主要根源。我在其中撰寫了除錯陳述句,因此您可以運行它并自己查看結果
using namespace std;
class Node
{
public:
int data;
Node *next;
Node()
{
next = nullptr;
}
Node(int data)
{
this->data = data;
}
Node(const Node &temp)
{
this->data = temp.data;
}
};
class Link
{
public:
Node *head;
int length = 0;
Link()
{
head = new Node();
}
~Link()
{
while (head != nullptr)
{
Node *p = head->next;
free(head);
head = p;
}
}
void insert(const Node &cache)
{
Node *temp = new Node(cache);
temp->next = head->next;
head->next = temp;
length ;
}
};
void Creatlist(Link &link)
{
char cache;
while (1)
{
cache = getchar();
if (cache == '\n')
break;
link.insert(Node(cache - '0'));
cout << cache << " ";
}
cout<<endl;
Node *p = link.head->next;
cout << "in the linklist:";
while (p != nullptr)
{
cout << p->data << " ";
p = p->next;
}
}
int main()
{
Link link;
cout<<"inut numbers:"<<endl;
Creatlist(link);
}```
uj5u.com熱心網友回復:
使用插入到串列前面的插入。所以你有“1”,然后是“2->1”......如果你想插入到最后,不要在頭部插入,而是Node* tail在類中Link加上一個 insert_end 函式作為
//...
Node* temp;
void insert_end(const Node &cache){
Node *temp = new Node(cache);
tail->next=temp;
tail=tail->next;
length ;
}
同樣在建構式集中tail=head
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515304.html
標籤:C
