数据结构-单链表的插入

来源:互联网 发布:淘宝待您处理的违规 编辑:程序博客网 时间:2024/05/20 20:20
#include<iostream>#include<stdlib.h>#define OK 1#define ERROR 0using namespace std;typedef struct LNODE{int data;struct LNODE *next;}Lnode;Lnode *Input(int n){Lnode *head,*p,*q;head=p=(Lnode*)malloc(sizeof(Lnode));p->next=NULL;for(int i=0;i<n;i++){int data;cin>>data;q=(Lnode*)malloc(sizeof(Lnode));q->data=data;q->next=p->next;p->next=q;p=q;}return head;}int Insert_Lnode(Lnode *LNode,int id,int data){Lnode *p,*q;p=LNode;int pos=0;while(p!=NULL){if(pos==id-1){q=(Lnode*)malloc(sizeof(Lnode));q->data=data;q->next=p->next;p->next=q;return OK;}pos++;p=p->next;}return ERROR;}void Show_Lnode(Lnode *LNode){Lnode *p;p=LNode->next;while(p!=NULL){cout<<p->data<<" ";p=p->next;}cout<<endl;}int main(){int n;while(cin>>n){Lnode *LNode=Input(n);while(1){int id,num;cout<<"输入插入的位置:";cin>>id;cout<<"输入插入的数值:";cin>>num;if(Insert_Lnode(LNode,id,num)){Show_Lnode(LNode); }else {cout<<"输入位置无效"<<endl; }}}return 0;}

原创粉丝点击