题一:编写一个算法判断链表中的数据项是否按从小到大排序,该链表的第一个节点由first指向。
题二:对于给定的整数n,编写一个算法把新节点插入到链表中第n个节点之后的位置,该链表的第一个节点由first指向。
题三:编写一个算法来颠倒一个链表,该链表的第一个节点由first指向。不要复制列表元素,而是重置链接和指针,是的first指向原来的最后一个节点,且节点之间的所有链接都反向。
#include <stdlib.h>
#include <stdio.h>
#define COUNT 5 //初始5个结点的链表
struct node
{
int num;
node *next;
};
node *creat(); //创建新链表(5个结点)
void print(node *); //遍历链表
node *add(node *); //添加\插入一个结点
int isSort(node *); //判断其数据项是否按从小到大排列
node *reverse(node *); //反转链表
void main()
{
node *first;
first = creat();
print(first);
first = add(first);
print(first);
first = reverse(first);
print(first);
if (0 == isSort(first))
printf("不是按从小到大排序\n");
else
printf("是按从小到大排序\n");
}
node *creat()
{
node *p1, *p2, *first;
first = NULL;
p1 = p2 = (node *)malloc(sizeof(node));
p1->num = 1; //头结点
first = p1;
for (int i = 1; i <= COUNT; i++)
{
p1 = (node *)malloc(sizeof(node));
p1->num = (100 * rand()) / (RAND_MAX * 1.0); //0~100间的随机数
p2->next = p1;
p2 = p1;
}
p2->next = NULL;
return first;
}
void print(node *first)
{
if (first == NULL)
{
printf("It's a empty list\n");
return;
}
node *first = first;
while (first != NULL)
{
printf("%d ", first->num);
first = first->next;
}
printf("\n");
}
int isSort(node *first)
{
if (first == NULL)
{
printf("It's a empty list\n");
return 0;
}
node *p = first;
while (p->next != NULL)
{
if (p->num > p->next->num)
return 0; //发现有后一个比前一个值小则结束查找
p = p->next;
}
return 1;
}
node *reverse(node *first)
{
node *pre, *cur, *nex;
if (first == NULL)
{
printf("It's a empty list\n");
return first;
}
pre = first;
cur = first->next;
while (cur)
{
nex = cur->next; //保存下一个结点
cur->next = pre; //当前结点的下一个结点指向前一个结点,实现反转
pre = cur; //pre和cur都依次后移一个结点
cur = nex;
}
first->next = NULL; //处理旧链表的头结点(即新链表的尾结点)
first = pre;
return first;
}