排序构建线性表educoder

花了38分钟才写出来,多练多练!!!
总结:用两个结点夹逼出待插入节点的位置 :定位好插入点后,当 p 为“NULL”时,插入点是链表头部;当 q 为“NULL”时,插入点是链表尾部;否则,插入点为 p 和 q 指向的两个结点之间。

#include <iostream>
using namespace std;

// 定义结点结构
struct node
{
    int data;  // 数据域
    node * next;  // 指针域,指向下一个结点
};

// 函数insertSort:链表排序插入
// 参数:h-链表头指针,t-指向要插入的结点
// 返回值:插入结点后链表的首结点地址
node * insertSort(node *h, node *t);

// 函数insertHead:链表头部插入
// 参数:h-链表头指针,t-指向要插入的结点
// 返回值:插入结点后链表的首结点地址
node * insertHead(node *h, node *t);

// 函数printList:输出链表,每个数据之间用一个空格隔开
// 参数:h-链表头指针
void printList(node *h);

// 函数insertTail:链表尾部插入
// 参数:h-链表头指针,t-指向要插入的结点
// 返回值:插入结点后链表的首结点地址
node *insertTail(node *h, node *t);

// 函数delList:删除链表,释放空间
// 参数:h-链表头指针
void delList(node *h);


node * insertSort(node *h, node *t)
{
    // 请在此添加代码,补全函数insertSort
    /********** Begin *********/
    if(h == NULL){
        t->next = NULL;
        return t;
    }
    node* q=h;
    node* p=NULL;
    while(q){
        if(q->data > t->data ){ //找到插点
            if(p == NULL){
                t->next = q;
                return t; //插入点是链表头部
            }
            p->next = t;
            t->next = q;
            return h;
        }else{
            p = q;
            q = q->next;
        }
    }
    if(q== NULL){
        p->next = t;
    }
    return h;
    /********** End **********/
}


int main()
{
	int n,i;
	node *t;
	node *head=NULL; //头指针为NULL,表示线性表为空,结点数为0
	//输入结点数
	cin>>n;
	for(i=0;i<n;i++)
	{
		//为新节点动态分配空间
		t = new node;
		cin>>t->data; //输入结点数据
		t->next=NULL;  //结点指针域值为空
		//调用函数插入结点,按data从小到大排序插入
		head = insertSort(head, t);
	}
	//输出链表
	printList(head);
	//删除结点,释放空间
	delList(head);

	return 0;
}
//函数delList:删除链表,释放空间
//参数:h-链表头指针
void delList(node *h)
{
	node *p=h; //指针p指向头结点,第一个要删除的结点
	while(p) //这个结点是存在的
	{
		h = h->next; //头指针h指向下一个结点(下一个结点的地址存在当前结点的指针域中,即h->next中
		delete p; //删除p指向的结点
		p = h; //p指向当前的头结点,即下一个要删除的结点
	}
}
//函数printList:输出链表,每个数据之间用一个空格隔开
//参数:h-链表头指针
void printList(node *h)
{
	cout<<"List:"; 
	while(h)
	{//h为真,即h指向的结点存在,则输出该结点的数据
		cout<<" "<<h->data;  //输出结点数据
		h=h->next;  //将该结点的指针域赋值给h,h就指向了下一个结点
	}
	cout<<endl; //输出换行符
}

//函数insertTail:链表尾部插入
//参数:h-链表头指针,t-指向要插入的结点
//返回值:插入结点后链表的首结点地址
node *insertTail(node *h, node *t)
{
	if(h==NULL) //空链表单独处理
	{
		t->next=NULL; //链表尾指针置为NULL
		return t; //返回第一个结点的地址(即链表头指针)
	}
	//非空链表的情况
	node *p=h;
	//让p指向最后一个结点
	while(p->next)
		p=p->next;
	p->next = t; //让最后一个结点的指针域指向结点t
	t->next=NULL; //链表尾指针置为NULL
	return h;  //返回第一个结点的地址(即链表头指针)
}

//函数insertHead:链表头部插入
//参数:h-链表头指针,t-指向要插入的结点
//返回值:插入结点后链表的首结点地址
node * insertHead(node *h, node *t)
{
	t->next=h;
	return t;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值