优化#include <iostream> using namespace std; struct node { int data; node* next; }; node* createlist(int array[], int n) { node *head = NULL, * tail = NULL; for (int i = 0; i < n; i++) { node* tmp = new node; tmp->data = array[i]; tmp->next = NULL; if (head == NULL) head = tail = tmp; else { tail->next = tmp; tail = tmp; } } return head; } void printlist(node* head) { for (node* pi = head; pi != NULL; pi->next) { cout << pi->data << " "; } } int main() { int n; cin >> n; int array[100]; for (int i = 0; i < n; i++) { cin >> array[i]; } printlist(createlist(array, n)); return 0; }
时间: 2024-01-15 16:03:26 浏览: 26
在这段代码中,可以进行以下几个优化:
1. 头文件只需要包含 <iostream>,不需要使用整个 namespace std。
2. 在创建链表时,可以使用一个指针变量来代替 tail 指针,减少一个变量的使用。
3. 在打印链表时,循环条件应该是 pi != NULL,而不是 pi->next != NULL。
以下是优化后的代码:
```
#include <iostream>
using std::cin;
using std::cout;
struct node {
int data;
node* next;
};
node* createlist(int array[], int n) {
node *head = nullptr, *p = nullptr;
for (int i = 0; i < n; i++) {
node* tmp = new node;
tmp->data = array[i];
tmp->next = nullptr;
if (head == nullptr)
head = p = tmp;
else {
p->next = tmp;
p = tmp;
}
}
return head;
}
void printlist(node* head) {
for (node* pi = head; pi != nullptr; pi = pi->next) {
cout << pi->data << " ";
}
}
int main() {
int n;
cin >> n;
int array[100];
for (int i = 0; i < n; i++) {
cin >> array[i];
}
printlist(createlist(array, n));
return 0;
}
```