首页 > 其他 > 详细

节点插入(线性表)

时间:2014-03-23 16:37:02      阅读:437      评论:0      收藏:0      [点我收藏+]

Problem E: 节点插入(线性表)

 

Description

有一个有序单链表(从小到大排序),表头指针为head,编写一个函数向该单链表中插入一个元素为x的结点,使插入后该链表仍然有序。

Input

输入长度n:5

输入数据:1 6 8 9 10

输入插入数据:7

Output

输出:1 6 7 8 9 10

Sample Input

4
1 2 3 4
6

Sample Output

1 2 3 4 6 

HINT

 

#include <iostream>
#define NULL 0
using namespace std; 
struct student
{
	int num;
	student *next;
};
int n;


student *creat(int m)
{
	student *head,*p1,*p2;
	p1=p2=new student;
	cin>>p1->num;
	head=NULL;
	n=0;
	while(p1->num!=NULL)
	{
		n=n+1;
		if(n==1)head=p1;
		else p2->next=p1;
		p2=p1;
		p1=new student;
		if(n==m)
		{break;}
		else
			cin>>p1->num;
	}
	p2->next=NULL;
	return(head);
}

void print(student *head)
{
	student *p;
	p=head;
	if(head!=NULL)
		do
		{
			cout<<p->num<<" ";
			p=p->next;
		}while(p!=NULL);
		
}
student *intset(student *head,student *stud)
{
	student *p0,*p1,*p2;
	p1=head;//使p1指向第一个结点
	p0=stud;//p0指向要插入的数值
	if(head==NULL)//原链表为空时
	{
		head=p0;
		p0->next=NULL;
	}
	else
	{
		while((p0->num>p1->num)&&(p1->next!=NULL))
		{
			p2=p1;//p2指向刚才的结点
			p1=p1->next;//p1指向下一结点
		}
		if(p0->num<=p1->num)
		{
			if(head==p1)//插入到第一个结点之前
				head=p0;
			else p2->next=p0;//将p0插入到结点之后
			p0->next=p1;
		}
		else//插到最后一个结点之后
		{
			p1->next=p0;
			p0->next=NULL;
		}
	}
	return (head);
}
int main()
{
	int m,num;
	cin>>m;
	student *head,*stud;
	student *creat(int);
	void print(student *);
	student *intset(student *,student *);
	head=creat(m);
	stud=new student;//开辟新的空间
	cin>>stud->num;
	intset(head,stud);
	print(head);
	return 0;
}


节点插入(线性表),布布扣,bubuko.com

节点插入(线性表)

原文:http://blog.csdn.net/u013629228/article/details/21867253

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!