单链表上的操作
2013-07-28 00:00
134 查看
题:假设有两个按元素值递增有序的线性表A 和B,均以单链表作存储结
构,试编写算法将A 表和B 表归并成一个按元素值递减有序的线性表
C,并要求利用原表的空间存放C。
构,试编写算法将A 表和B 表归并成一个按元素值递减有序的线性表
C,并要求利用原表的空间存放C。
#include <iostream> #define M 3 #define N 2 using namespace std; struct Link{ int x; struct Link *next; }; void main(){ //Creating two links; struct Link *Ahead=new Link,*Ar=Ahead; Ahead->next=NULL; struct Link *Bhead=new Link,*Br=Bhead; Bhead->next=NULL; //Creating M nodes of link A; cout<<"Input "<<M<<" number(s) which must be inputted in ascending order (link A):"; for(int i=0;i<M;i++){ struct Link *p=new Link;//Creating a new node; cin>>p->x; p->next=NULL; Ar->next=p;//Letting the last node's next point to the newly-created node; Ar=p;//*p has become the last node and let r point to it.Remember,r always points to the last node; } //Creating N nodes of link B; cout<<"Input "<<N <<" number(s) which must be inputted in ascending order (link B):"; for(i=0;i<N ;i++){ struct Link *p=new Link;//Creating a new node; cin>>p->x; p->next=NULL; Br->next=p;//Letting the last node's next point to the newly-created node; Br=p;//*p has become the last node and let r point to it.Remember,r always points to the last node; } //Combining A with B to get C which should be in descend order; Ar=Ahead->next; Br=Bhead->next; struct Link *Chead=new Link,*Cr;//Creating a new head node; Chead->next=NULL; while(Ar&&Br){ if(Ar->x<=Br->x) { struct Link *Ap=Ar; Ar=Ar->next;//Reserving the link; Ap->next=Chead->next;//Insert Chead->next=Ap; } else{ struct Link *Bp=Br; Br=Br->next;//Reserving the link; Bp->next=Chead->next;//Insert Chead->next=Bp; } } //Inserting the remain nodes; struct Link *r=Ar?Ar:Br;//Let r point to the point which is not NULL; if(r){//Ensure r is not NULL; struct Link *s=r->next;//Reserving the link; while(s){//not only one node; //Insert r->next=Chead->next; Chead->next=r;//cout<<r->next->x<<endl; r=s;//pointing to the next node; s=s->next; } //insert the last node; r->next=Chead->next; Chead->next=r;cout<<r->next->x<<endl; } //Show these elements in the link; Cr=Chead->next; while(Cr){ cout<<Cr->x<<" "; Cr=Cr->next; } cout<<endl; }
相关文章推荐
- 单向链表的操作
- C++实现链表基本操作
- 单向链表基本操作(C语言实现)
- 链表的基本操作
- 实现无头结点单链表的基本操作函数
- 双向链表的基本操作实现
- 双链表基本操作
- 【c语言】单链表的基本操作
- c用餐管理系统----------文件链表相关操作
- 单链表基本操作的C语言实现(链式存储结构)
- 典型的几个链表操作-逆序和重排
- C:链表的操作,如何创建一个链表并打印
- 猴子选大王改编;关于环形链表的建立,删除,插入操作演示
- linux内核list.h中对链表的操作
- 链表栈的基本操作
- 链表插入删除操作
- 链表(单双链表)用法与基本操作(构建、查找、插入、删除)实现
- C语言中关于链表的一些操作
- C语言实现带头结点的链表的创建、查找、插入、删除操作
- 循环链表的算法操作