C++使用数组构造链表
1、链表的定义
struct Node{
int value;
struct Node* next;
};
2、使用数组构造链表
Node *createList_array(int *a, int n){
Node *root = new Node();
Node *pnode = root;
for (int i = 0; i < n - 1; ++i){
root->value = a[i];//当前节点
root->next = NULL;
Node *p = new Node();//下一个结点
p->value = a[i + 1];
p->next = NULL;
root->next = p;// 连接 当前节点 与 下一个结点
root = root->next;
}
root->next = NULL;//这一句 最重要!!
return pnode;
}
3、显示链表的两种方法
void disp(Node* node){
cout << "--------------------1" << endl;
if (node == NULL)return;
while (node != NULL){
cout << node->value;
if (node->next) cout << "->";
node = node->next;
}
cout << endl;
}
void disp2(Node* node){
cout << "--------------------2" << endl;
if (node == NULL)return;
cout << node->value;
while (node->next != NULL){
cout << "->";
node = node->next;
cout << node->value;
}
cout << endl;
}
4、测试:
int main(){
int a[] = { 1, 3, 5, 7, 9 };
int n = sizeof(a) / sizeof(a[0]);
Node *pnode = createList_array(a, n);
disp(pnode);
disp(pnode);
disp2(pnode);
disp2(pnode);
}