首页 > 编程语言 >Inserting a node at nth position【1月17日学习笔记】

Inserting a node at nth position【1月17日学习笔记】

时间:2024-01-17 11:02:09浏览次数:29  
标签:Inserting node run temp 17 next 指向 节点

点击查看代码
//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();
}
                                                          

标签:Inserting,node,run,temp,17,next,指向,节点
From: https://www.cnblogs.com/whvivy/p/17969451

相关文章