#include<iostream> #include<algorithm> using namespace std; typedef struct Node{ int data; Node *next; }LNode, *LinkList; void Creat(LinkList &L){ L = new Node; L->next = NULL; cout << "你已经成功创建了一个队列" << endl; } void Insert(LinkList &L, int n){ cout << "请输入" << n << "个需要插入的元素" << endl; LNode *p, *cur; cur = L; for(int i = 0; i < n; i++){ p = new LNode; cin >> p->data; p->next = NULL; cur->next = p; cur = p; } cout << "创建结束" << endl; } void Pop(LinkList &L){ if(L->next == NULL){ cout << "弹出错误" << endl; return; } LNode *p, *q; p = L->next; q = p->next; L->next = q; cout << "队顶元素是 " << p->data << endl; delete p; } int main(){ LinkList L; Creat(L); cout << "输入插入长度" << endl; int n; cin >> n; Insert(L, n); while(L->next){ Pop(L); } return 0; }
#include<iostream> using namespace std; typedef struct LNode //定义单链表 { int data; struct LNode *next; }LNode,*LinkList; void InitList_L(LNode* &L) //创建单链表 { L=new LNode; L->next=NULL; } void input(LinkList &L,int n) //依次往单链表L里输入数据 { int i; LinkList p,r; r=L; cout<<"请输入该表的元素(按非递减的顺序):"; for(i=0;i<n;i++) { p=new LNode; cin>>p->data; p->next=NULL; r->next=p; r=p; } } void output(LinkList L) //依次输出单链表里的每个元素 { int i=0; LNode *p; p=L->next; while(p) { if(i) cout<<","; cout<<p->data; p=p->next; i=1; } } void MergeList_L(LinkList &LA,LinkList &LB,LinkList &LC) //算法2.16 链式有序表的合并 { //已知单链表LA和LB的元素按值非递减排列 //归并LA和LB得到新的单链表LC,LC的元素也按值非递减排列 //以下填空缺部分 LNode *p, *q, *cur, *temp; p = LA->next; q = LB->next; cur = LC; while(p && q){ if(p->data <= q->data){ temp = new LNode; temp->data = p->data; temp->next = NULL; cur->next = temp; cur = temp; p = p->next; } else{ temp = new LNode; temp->data = q->data; temp->next = NULL; cur->next = temp; cur = temp; q = q->next; } } if(p){ cur->next = p; } if(q){ cur->next = q; } } //MergeList_L() int main() { LinkList La,Lb,Lc; int num_a,num_b; cout<<"请输入非递减单链表a的个数n:"; cin>>num_a; InitList_L(La); //La表的创建 input(La,num_a); //依次往单链表La里输入数据 cout<<"请输入非递减单链表b的个数n:"; cin>>num_b; InitList_L(Lb); //Lb表的创建 input(Lb,num_b); //依次往单链表La里输入数据 InitList_L(Lc); MergeList_L(La,Lb,Lc); //将单链表La和Lb进行合并 cout<<"非递减单链表a,b合并后的非递减单链表c为: "; //输出合并后的单链表Lc output(Lc); cout<<endl; return 0; }