点击查看代码
//Inserting a node at nth position
#include<iostream>
using namespace std;
struct node {
int data;
node* next;
};
node* A;//全局头指针
void insert(int x, int n) {
node* temp = new node;//temp是局部变量,在stack区,每次调用更新
temp->data = x;
temp->next = NULL;//创建新节点(新节点在heap区,通过全局头指针索引)
if (n == 1) {
temp->next = A;//新节点尾巴指向1节点
A = temp;//头指针·指向新节点
return;
}//inserting at begining
node* run = A;
for (int i = 0; i < n - 2; i++) {
run = run->next;
}//循环n-2次,结束时run指向n-1节点
temp->next = run->next;//新节点尾巴指向n节点(左边尾巴指向右边尾巴指向的节点)
run->next = temp;//n-1节点尾巴指向新节点
}
void print() {
node* run = A;
while (run != NULL) {
cout << run->data << " ";
run = run->next;
}
cout << endl;
}
int main() {
A = NULL;
insert(2, 1);
insert(3, 2);
insert(4 ,1);
insert(5, 2);
print();
}