链表:在任意位置插入一个节点
#include<iostream>using namespace std;struct Node{int data;Node* next;};Node* head ;//接收两个参数:插入的数据和想要插入的位置void Insert(int data,int n){Node* temp1 = new Node;temp1->data = data;temp1->next
·
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* head ;
//接收两个参数:插入的数据和想要插入的位置
void Insert(int data,int n)
{
Node* temp1 = new Node;
temp1->data = data;
temp1->next = NULL;
if(n == 1)
{
temp1->next = head;
head = temp1;
return;
}
Node* temp2 = head;
for(int i = 1; i <= n - 2; i++)//利用循环从第一个节点到第n-1个节点
{
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
void Print()
{
Node* temp = head;
while(temp != NULL)
{
printf("%d ",temp->data);
temp = temp -> next;
}
printf("\n");
}
int main()
{
head = NULL;//初始链表为空
Insert(2, 1);//List: 2
Insert(3, 2);//List: 2, 3
Insert(4, 1);//List: 4, 2, 3
Insert(5, 2);//List: 4, 5, 2, 3
Print();
return 0;
}

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)