当前位置 博文首页 > 爱新觉罗?炒饭的博客:考前紧急复习——链表的一些基本操作和一
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Lnode
{
int data;
struct Lnode *next;
} Lnode;
void CreateList1(Lnode *H,int n) //头插法建立链表
{
int i;
for (i = 0; i < n;i++)
{
Lnode *p = (Lnode *)malloc(sizeof(Lnode));
scanf("%d", &p->data);
p->next = H->next;
H->next = p;
}
}
void CreateList2(Lnode *H,int n) //尾插法建立链表
{
int i;
Lnode *q = H;
for (i = 0; i < n;i++)
{
Lnode *p = (Lnode *)malloc(sizeof(Lnode));
scanf("%d", &p->data);
p->next = q->next;
q->next = p;
q = p;
}
q->next = NULL;
}
void Output(Lnode *H) //输出链表
{
Lnode *p;
p = H->next;
while(p!=NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
int Length(Lnode *H) //求链表长度
{
int count = 0;
Lnode *p = H->next;
while(p!=NULL)
{
count++;
p = p->next;
}
return count;
}
int Search(Lnode *H,int x) //查找元素并返回位置,没找到则返回0
{
int count = 0;
Lnode *p = H->next;
while (p != NULL)
{
count++;
if(p->data==x)
return count;
p = p->next;
}
return 0;
}
int SearchPre(Lnode *H,int x) //查找元素x的前驱
{
Lnode *pre = H;
Lnode *p = H->next;
while(p!=NULL)
{
if(p->data==x)
return pre->data;
else
{
pre = p;
p = p->next;
}
}
return 0;
}
void Delete(Lnode *H,int x) //删除元素x
{
Lnode *pre = H;
Lnode *p = H->next;
while(p!=NULL)
{
if(p->data==x)
{
Lnode *s = p;
pre->next = p->next;
p = p->next;
free(s);
}
else
{
pre = p;
p = p->next;
}
}
}
void Insert(Lnode *H,int x) //在递增有序的链表里插入一个元素仍保持有序
{
Lnode *pre = H;
Lnode *p = H->next;
Lnode *q = (Lnode *)malloc(sizeof(Lnode));
q->data = x;
while(p!=NULL&&p->data<x)
{
pre = p;
p = p->next;
}
pre->next = q;
q->next = p;
}
void CreateSortList(Lnode *H,int n) //采用尾插法建立一个递增有序链表
{
int i, x;
for (i = 0; i < n;i++)
{
scanf("%d", &x);
Insert(H, x);
}
}
int main()
{
Lnode *H = (Lnode *)malloc(sizeof(Lnode));
H->next = NULL;
int n;
// scanf("%d", &n);
// CreateList2(H,n); //CreateList1(H,n)
// Output(H);
// // puts("");
// // printf("%d\n",Length(H));
// int x;
scanf("%d", &n);
// printf("%d\n", Search(H,x));
// printf("%d\n", SearchPre(H, x));
// Delete(H, x);
// Insert(H, x);
CreateSortList(H, n);
Output(H);
system("pause");
return 0;
}
顺便把学弟的一道链表题偷过来做一做
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
typedef struct sb
{
int no;
struct sb *next;
} sb;
int Check(int x) //判断是否为素数
{
int i;
for (i = 2; i <= sqrt(x);i++)
{
if(x%i==0)
return 0;
}
return 1;
}
void Insert(sb *H,int x) //插入元素
{
int MaxNum = 0;
sb *p = H->next;
sb *pre = H;
sb *index, *q;
while(p!=NULL)
{
if(Check(p->no)&&p->no>MaxNum)
{
q = pre;
index = p;
MaxNum = p->no;
}
pre = p;
p = p->next;
}
sb *s = (sb *)malloc(sizeof(sb));
s->no = x;
q->next = s;
s->next = index;
}
void Output(sb *H) //输出链表
{
sb *p = H->next;
while(p!=NULL)
{
printf("%d ", p->no);
p = p->next;
}
printf("\n");
}
int main()
{
sb *H = (sb *)malloc(sizeof(sb));
H->next = NULL;
int n, m;
while(scanf("%d%d",&n,&m)!=-1)