我寫了一個代碼,要求用戶輸入一個自定義串列,我想顯示它,但它只顯示頭節點。
我想知道問題是來自顯示功能還是輸入功能。我想稍后洗掉顯示功能,但我希望創建我的串列。
這是我的代碼:
#pragma once
#include <cstddef>
#include <iostream>
using namespace std;
struct node {
char data;
node* next;
};
node* inputList();
void displayList(node*);
int exercice1() {
node* head;
head = inputList();
displayList(head);
return 0;
}
node* inputList() {
node* tmp;
node* cur, *head;
int n;
do {
cout << "enter the number of nodes: ";
cin >> n;
} while (n <= 0);
tmp = new node;
cout << "enter the values inside each node: ";
cin >> tmp->data;
head = tmp;
cur = tmp;
for (int i = 1; i < n; i ) {
tmp = new node;
cur = cur->next;
cout << "enter a node: ";
cin >> tmp->data;
cur = tmp;
}
cur->next = NULL;
return head;
}
void displayList(node* head) {
if (head != NULL) {
cout << head->data;
displayList(head->next);
}
}
uj5u.com熱心網友回復:
inputList無法將節點鏈接在一起。我們可能會逃脫類似的事情
tmp = new node;
cur->next = tmp; // point current node's next at new node
cur = cur->next;
但這是一種更清潔的方法:
node* inputList() {
node * head; // storage for the start of the list. Keeps track so we
// know what to return when we're done.
node ** insert = &head; // store where we're going to insert a node rather than
// tracking the current node with another variable.
// this is both tmp and cur by always pointing at where
// the next node is going to go.
int n;
do {
cout << "enter the number of nodes: ";
cin >> n;
} while (n <= 0);
*insert = new node; //node goes right into head
cout << "enter the values inside each node: ";
cin >> (*insert)->data;
insert = &(*insert)->next; // now the insertion point points at head's next
for (int i = 1; i < n; i ) {
*insert = new node; // new node gets linked right in next
cout << "enter a node: ";
cin >> (*insert)->data;
insert = &(*insert)->next; // advance to next of the node we just added
}
*insert = NULL; // terminate list by pointing the insertion point at NULL
return head;
}
現在他已經抽象head成另一個插入點,例如next,我們可以消除一些重復的代碼:
node* inputList() {
node * head;
node ** insert = &head; // head is no different from a next. It just
// has a different name
int n;
do {
cout << "enter the number of nodes: ";
cin >> n;
} while (n <= 0);
// no special handling for head.
for (int i = 0; i < n; i ) { // iteration now starts at 0. The loop
// builds all of the nodes.
*insert = new node;
cout << "enter a node: ";
cin >> (*insert)->data;
insert = &(*insert)->next;
}
*insert = NULL;
return head;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426378.html
