无头链表有序插入

无头链表有序插入

#include <stdio.h>
#include <stdlib.h>

typedef struct list {
	int num;
	struct list *pNext;
}Node,*pNode;

//有序插入
void listInsertSort(pNode * pHead, pNode* pTail, int value) {
	pNode pNew = (pNode)calloc(1, sizeof(Node));//申请空间,自带memset
	pNode pCur = *pHead, pPre = *pHead;//初始化
	pNew->num = value;
	if (NULL == *pHead) { //判断链表是否为空
		*pHead = pNew;
		*pTail = pNew;
	}
	else if (pCur->num > value) { //判断第一个节点的值是否大于插入的值,然后用头插法
		pNew->pNext = *pHead;
		*pHead = pNew;
	}
	else {  
		while (pCur) {  //否则遍历链表
			if (pCur->num > value) {
				pPre->pNext = pNew;
				pNew->pNext = pCur;
				break;
			}
			pPre = pCur;
			pCur = pCur->pNext;
		}
		if (NULL==pCur) { //要插入的值最大,尾插法
			pPre->pNext = pNew;
			*pTail = pNew;
		}
	}
}

//打印链表
void printlist(pNode pHead) {
	while (pHead) {
		printf("%3d", pHead->num);
		pHead = pHead->pNext;
	}
	printf("\n");
}

int main() {
	pNode pHead = NULL, pTail = NULL;
	int num;
	while (scanf("%d", &num) != EOF) {
		listInsertSort(&pHead, &pTail, num);
	}
	printlist(pHead);
	return 0;
}

在这里插入图片描述

关于函数形参的指针问题见 一级指针与二级指针简单理解

源代码来源于B站王道论坛

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值