#include<stdlib.h>
#include<stdio.h>
typedef int Elemtype;
typedef struct Node{
Elemtype data;
struct Node * next;
}Node, *LinkList;
//初始化链表
void InitList(LinkList *L) {
*L = (Node*)malloc(sizeof(Node));
(*L)->next = NULL;
}
//创建链表
void CreateList(LinkList L)
{
Node *rear = L,*s;
int num;
printf("List is creating(input 99999 to end):\n");
scanf("%d", &num);
while (num != 99999) {
s = (Node*)malloc(sizeof(Node));
s->data = num;
rear->next = s;
s->next = NULL;
rear = s;
scanf("%d", &num);
}
}
//展示内容
void DisplayList(LinkList L)
{
Node *p = L->next;
if (!p) {
printf("\nThe list is empty.\n");
return;
}
printf("\n");
while (p) {
printf("%d, ", p->data);
p = p->next;
}
printf("\n");
}
//就地逆置
void ReverseList(LinkList L)
{
if (L->next == NULL) {
printf("空表无法逆置\n");
return;
}
Node *p = L->next,*temp;
L->next = NULL;
while (p) {
temp = p->next;
p->next = L->next;
L->next = p;
p = temp;
}
}
//以第一结点的元素为依据,将所有小于它的放在左边,大于它的放在右边
void AdjustListByValue(LinkList L)
{
if (L->next == NULL) {
printf("空链表,无须调整\n");
return;
}
Node *pFirst = L->next,*pre = L->next, *p = pre->next,*temp;
while (p) {
//如果比首元素小,就将其从中删除,头插法插入头部
if (p->data < pFirst->data) {
pre->next = p->next;
temp = p->next;
p->next = L->next;
L->next = p;
p = temp;
}//否则直接连接在原有链表上
else {
pre = p;
p = p->next;
}
}
}
//链表从高位到低位存储二进制数的各位, 然后加1得到结果链表
//在原有的空间上操作
//思路:从高位到低位找最后一个0,如若找到则将其置为1,后续全部置为0;否则新增一个值为1的新结点,其余全部设置为0
void BinaryAdd(LinkList L) {
Node *p = L->next, *lastZero = L,*newOne;
while (p) {
if (p->data == 0)
lastZero = p;
p = p->next;
}
if (lastZero != L) {
lastZero->data = 1;
}
else {
newOne = (Node *)malloc(sizeof(Node));
newOne->data = 1;
newOne->next = L->next;
L->next = newOne;
lastZero = newOne;//注意:如果不给lastZero赋值,则会在后面把新的结点的1又改成0
}
lastZero = lastZero->next;
while (lastZero)
{
lastZero->data = 0;
lastZero = lastZero->next;
}
}
int main()
{
LinkList L1, L2;
InitList(&L1);
InitList(&L2);
CreateList(L1);//15 12 6 8 45 32 14 99999
DisplayList(L1);// 1 1 1 0 1 0 1 1 99999 1 1 1 1 1 1 1 1 99999
CreateList(L2);
DisplayList(L2);
ReverseList(L1);
DisplayList(L1);
AdjustListByValue(L1);
DisplayList(L1);
BinaryAdd(L2);
DisplayList(L2);
return 0;
}
带头结点单链表就地逆置、二进制加一、以第一元素划分链表
最新推荐文章于 2025-04-03 00:30:00 发布
该博客展示了链表的基本操作,包括初始化、创建、显示、逆置、按值调整和二进制加1等。通过C语言实现,详细解释了每个操作的逻辑和步骤,适合理解链表数据结构和算法的初学者。
5787

被折叠的 条评论
为什么被折叠?



