单链表上的操作

1、已知带头结点的动态单链表L 中的结点是按整数值递增排序的,试写
一算法将值为x 的结点插入到表L 中,使L 仍然有序。

#include <iostream.h>
#define M 5
struct Link{
	int x;
	struct Link *next;
};
void main(){
    //Creating a link;
    struct Link *head=new Link,*r=head;
	head->next=NULL;
    //Creating M nodes;
	cout<<"Input "<<M<<" number(s) which must be inputted in ascending order:";
	for(int i=0;i<M;i++){
        struct Link *p=new Link;//Creating a new node;
	    cin>>p->x;
		p->next=NULL;
		r->next=p;//Letting the last node's next point to the newly-created node;
		r=p;//*p has become the last node and let r point to it.Remember,r always points to the last node;
	}
	//Creating a node to insert into the link;
    struct Link *p=new Link;
    cout<<"Input x of the node which you want to insert into the link:";
	cin>>p->x; 
	p->next=NULL;
	//Inserting the node into the link
    struct Link *pr=head;
	r=head->next;//pr points to the node before *r;
    while(r){
		if(r->x>=p->x) break;//Having found the position belonging to the node *p;
		pr=r;
		r=r->next;//If not,let pr and r point to their next node; 
	}
	if(r){//Find it
	    pr->next=p;
		p->next=r;
	} 
	else{//Not found
        pr->next=p;
	}
	//Show these elements in the link;
	r=head->next;
	while(r){
		cout<<r->x<<" ";
		r=r->next;
	}
	cout<<endl;
}

你可能感兴趣的:(单链表上的操作)