#include <bits/stdc++.h> //节点结构体 using namespace std; struct Node{ int data; Nodenext; }; //创建单链表:返回单链表的头结点 Node createList(){ Node* h=new Node;//创建了一个新节点 Node* r=h;//只有一个节点的时候 头尾节点都是同一个 //输入数据构建链表 输入-1结束 Node* p; int a; while(1){ cin>>a; if(a==-1){ break; } p=new Node; p->data=a; p->next=NULL; //将新节点连接在链表的尾部 r->next=p; r=p; } return h; } void printList(Nodeh){ Node t=h->next; while(t!=NULL){ cout<data<<" "; t=t->next; } } bool insert(Node* h,int n,int index){ Node* p=h; for(int i=1;i<index;i++){ p=p->next; } Node* t=new Node; t->data=n; t->next=p->next; p->next=t; return true; } int main() { Node* h=createList(); int n,index; cin>>n>>index; insert(h,index,n); printList(h); return 0; }

0 条评论

目前还没有评论...