c语言之链表学习



#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAX 1000

/* 编一C程序,它能读入两组整数(每组整数都以-9999为结束标记,个数都不大于1000),
并以从小到大的次序输出既在第一组整数中也在第二组整数中的所有整数(同一个整数不能输出两次)。
(输入时,两个相邻的整数用空格隔开)。*/

/*它能读入一串整数(以-9999为结束标记),再以与输入次序相反的次序输出这串整数(输入、出时,两个相邻的整数用空格隔开)*/

typedef struct Node
{
int d;
struct Node *next;
}NODE,*PNODE;

void printLinkList(PNODE head)
{
PNODE p = head;
while((p=p->next)!=NULL)
{
printf("%d ",p->d);
}
}
//初始化链表 课本上
PNODE initLinklist()
{
PNODE head,tail,p;
int n;
head = (PNODE)malloc(sizeof(NODE));
tail=head;
scanf("%d",&n);
while(n!=-9999)
{
p = (PNODE)malloc(sizeof(NODE));

p->d=n;
tail->next=p;
tail=p;
scanf("%d",&n);
}
tail->next=NULL;
return head;
}


PNODE initLinklist2()
{
PNODE head,h,p;
int d;
head=h=(PNODE)malloc(sizeof(NODE));
scanf("%d",&d);
if(d==-9999)return head;
do
{
p =(PNODE)malloc(sizeof(NODE));
p->d=d;
p->next=NULL;
h->next=p;
h=p;
scanf("%d",&d);
}while(d!=-9999);
return head;
}
//初始化链表,输入 12345 打印54321
PNODE initLinklist3()
{
PNODE head,tail;
int d;
head=(PNODE)malloc(sizeof(NODE));
head->next=NULL;
scanf("%d",&d);
if(d==-9999)return head;
do
{
tail =(PNODE)malloc(sizeof(NODE));
tail->d=d;
if(head->next==NULL)
{
head->next=tail;
tail->next=NULL;
}
else
{
tail->next=head->next;
head->next=tail;
}
scanf("%d",&d);
}while(d!=-9999);
return head;
}


//冒泡排序
PNODE maopaoSort(PNODE head)
{
PNODE p1,p2;
int temp;
p1=head->next;
for(;p1;p1=p1->next)
{
for(p2=p1->next;p2;p2=p2->next)
{
if(p2->d<p1->d)
{
temp=p2->d;
p2->d=p1->d;
p1->d=temp;
}
}
}
return head;
}


void deleteDuplicate(PNODE n){
while(n)
{
n=n->next;
if(n&&n->next&&n->d==n->next->d)
{
n->next=n->next->next;
}
}
}
//前提已经排序
void deleteNoDuplicate(PNODE head)
{
PNODE p;
p=head->next;
while(p)
{
if(p->next&&p->d==p->next->d)
{
p->next=p->next->next;//本应该考虑内存释放

}
p=p->next;

}
}
/*
插入排序
*/

void insertSort1(PNODE head)
{
PNODE h,p1,p2;
if(!head->next||!head->next->next)return;
h=head;
p2=head->next->next;//第二个链表的起始地址
h->next->next=NULL;//第一个节点指向NULL,链表分段
while(p2)
{
p1=p2->next;
h=head;//h归位
while(h->next)
{
if(h->next->d>p2->d)
{
p2->next=h->next;
h->next=p2;
break;
}
else
{
h=h->next;
}
}
if(h->next==NULL)
{
h->next=p2;
p2->next=NULL;
}
p2=p1;//P2归位
}

}
void main()
{
PNODE a;
printf("input a:\n");
a = initLinklist3();
printLinkList(a);
printf("\n");
maopaoSort(a);
printLinkList(a);
//deleteNoDuplicate(a);
//printLinkList(a);
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值