首页 > 其他 > 详细

面向对象程序设计(二)---链表

时间:2021-04-08 17:56:07      阅读:11      评论:0      收藏:0      [点我收藏+]

本次学到知识点:链表动态create、 Insert、delete.

pta例题

7-1 可怕的素质

题解

#include<stdio.h>
#include<stdlib.h>
#define len sizeof(struct people)
struct people{
	int name;
	struct people *next;
};
int cnt=1;
void print(struct people *head){
	struct people *p;
	p = head;
	if(head!=NULL){
		do{
			printf("%d",p->name);
			p = p->next;
			if(p!=NULL){
				printf(" ");
			}
		}while(p!=NULL);
	}
}
struct people *insert(struct people *head,int i){
	struct people *p;
	struct people *q;
	p = head;
	q = (struct people *)malloc(len);
	q->name = cnt++;
	if(i==0){
		q->next=head;
		head = q;
	}else{
		do{
			if(p->name==i){
				q->next=p->next;
				p->next=q;
				break;
			}else{
				p=p->next;
			}
		}while(p!=NULL);
	}
	return(head);
}
int main(){
	int n;
	scanf("%d",&n);
	struct people *head;
	int o;
	head = (struct people *)malloc(len);
	head->name=cnt;
	cnt++;
	head->next=NULL;
	int hi;
	scanf("%d",&hi);
	for(int i=0;i<(n-1);i++){
		scanf("%d",&o);
		head = insert(head,o);
	}
	print(head);
	return 0;
}

Create

#define LEN sizeof(struct student)
struct student  *creat( )
{
  	struct student  *head=NULL, *p1,*p2;
        int n=1;
  	p1=p2=(struct student *)malloc(LEN);
        scanf("%ld,%f",&p1->num,&p1->score);
  	while(p1->num!=0) 
  	{
    		if(n==1) head=p1;
		else   p2->next=p1;

    		p2=p1;
		p1=(struct student *)malloc(LEN);
		scanf("%ld,%f",&p1->num,&p1->score);
		n++;
  	}
  	
  	p2->next=NULL;
  	return(head);
} 

Insert

struct node *insert(struct node *head, int i)
{
  	struct node *p,*q;
  	p=head;
          q=(struct student *)malloc(LEN);
  	scanf("%ld,%f",&q->num,&q->score);
           if(i==1){q->=head; head=q;}
           else
  	{
    	        for(j=1;j<i-1;j++)
                          p=p->next;
                  q->next=p->next;
                  p->next=q;
  	}
  	return(head);
} 

Delete

struct node *del(struct node *head, int d )
{
  	struct node *p1,*p2;
  	p1=head;
  	while(                                                   ) //查找要删除的结点
  	{
    		p2=p1;
    		p1=p1->next;
  	}
  	if(p1->num==d)   //删除结点
  	{
    		if(p1==head) head=p1->next;
   		else        p2->next=p1->next;
    		free(p1);          //释放所删除结点的空间
  	}
  	else printf("找不到该结点\n");
  	return(head);
} 

Print

void print (struct student *head)
{ 
	struct student *p;
   	p=head;
   	if (head !=NULL)
      	do    
		{ 
			printf("%ld,%f",p->num,p->score);
                	p=p->next;
            } while (p!=NULL);
}

面向对象程序设计(二)---链表

原文:https://www.cnblogs.com/Xuuxxi/p/14556266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!