我觉得链表像是更灵活的数组
它和它的名字一样,像一根链子一样连起来,具有连续性。
首先他的灵魂在:
typedef struct node{
int data;//链表里存入的数据
struct node *next;//有它才能连成一根链子,形成链表
}node;
我们直接看题叭
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
node *head=NULL;
node *tail=NULL;
node *createnode(int data){//创建节点
node *nn=(node*)malloc(sizeof(node));
nn->data =data;
nn->next =NULL;
return nn;
}
void addnode(int data){//增加节点
node *nnode=createnode(data);
if(head==NULL){
head=nnode;
}
else tail->next =nnode;
tail =nnode;
}
int findmax(){//遍历查找链表里的最大值
node *temp=head;
int max=0;
while(temp){
if(temp->data >max)
max=temp->data ;
temp=temp->next ;
}
return max;
}
int findmin(){//遍历查找链表里的最小值
node *temp=head;
int min=1000;
while(temp){
if(temp->data <min)
min=temp->data ;
temp=temp->next ;
}
return min;
}
void deletenode(int data){//删除指定的节点
node *posenode=head->next ;
node *prenode=head;
if(posenode==NULL)return;
if(head->data ==data){
free(prenode);
head=posenode;
return;
}
while(posenode->data !=data){
prenode=posenode;
posenode=prenode->next;
if(posenode==NULL)return;
}
prenode->next=posenode->next;
free(posenode);
}
void printnode(){//打印链表,检查写对了没有而已
node *temp=head;
while(temp){
printf("%d ",temp->data );
temp=temp->next;
}
printf("\n");
}
float vvvnode(){
node *temp=head;
float sum=0,shu=0;
while(temp){
sum+=temp->data ;
shu++;
temp=temp->next ;
}
return(sum/shu);
}
int main()
{
int scord;
while(~scanf("%d",&scord)){
if(scord==-1)break;
addnode(scord);
}
int max=findmax();
int min=findmin();
deletenode(max);
deletenode(min);
// printnode();//检查自己有没有写对
printf("%.2f",vvvnode());
return 0;
}
觉得自己在删除指定节点那里写的太麻烦了,不知道如果指定节点在头节点那里该怎么一步写到位,留着下次改改叭。
plmm的方法可以解决一下这个问题,就是将head的值一开始就定下来,键盘输入的节点从head后开始连接,这样就不用处理头节点的删除工作啦!
plmm的代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node* next;
}node;
node* creatnode(){
node* head=(node*)malloc(sizeof(node));
head->data=-1;
head->next=NULL;
node* tail=head;
int a=-1;
while(1){
scanf("%d",&a);
if(a==-1){
break;
}
node* newnode=(node*)malloc(sizeof(node));
newnode->data=a;
newnode->next=NULL;
tail->next=newnode;
tail=newnode;
}
return head;
}
int findmin(node* head){
int min = 99999;
node* p=head->next;
while(p!=NULL){
if(p->data<min)
min=p->data;
p=p->next;
}
return min;
}
int findmax(node* head){
int max = -1;
node* p = head->next;
while(p!=NULL){
if(p->data>max)
max=p->data;
p = p->next;
}
return max;
}
void delet(node* head,int deldata){
node* p = head;
node* c = head->next;
while(c!=NULL){
if(c->data==deldata){
break;
}
p = c;
c = c->next;
}
p->next = c->next;
free(c);
}
double arry(node* head){
node* p = head->next;
int sum=0,a = 0;
while(p!=NULL){
sum+=p->data;
p = p->next;
a++;
}
double arry = sum/(double)a;
return arry;
}
int main(){
node* head = creatnode();
int min=findmin(head);
int max = findmax(head);
delet(head,min);
delet(head,max);
double a=arry(head);
printf("%.2lf",a);
return 0;
}