单链表上的操作

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;
}

转载于:https://my.oschina.net/u/877340/blog/147188

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值