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

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

c++链表的动态创建,插入,删除和输出

#include<iostream>

using namespace std;

struct test{
    int n;
    test * next;
};

//print
void print(test * head){
    for(test * p = head;p != NULL;p = p -> next) cout << p -> n << ' ';
}

//ins
void ins(test * head,int n,int k){
    test * p1 = new test;
    p1 -> n = n;
    
    if(k == 0) p1 -> next = head,head = p1;
    else{
        int cnt = 0;
        for(test * p = head;p != NULL;p = p -> next){
            cnt ++;
            if(cnt == k) p1 -> next = p -> next,p -> next = p1;
        }
    }
}

//del
void del(test * head,int k){
    if(k == 0) head = head -> next;
    else{
        int cnt = 0;
        for(test * p = head;p != NULL;p = p -> next){
            cnt ++;
            if(cnt == k){
                p -> next = p -> next -> next;
                break;
            }
        }
    }
}

int main(){
    //creat
    test * head = NULL;
    test * p1, * p2;
    p2 = head;
    
    for(int i = 0;i < 5;i ++){
        p1 = new test;
        cin >> p1 -> n;
        
        if(i == 0) head = p1;
        else p2 -> next = p1;
        p2 = p1;
    }
    p2 -> next = NULL;
    
    ins(head,11,2);
    print(head);
    
    cout << endl;
    
    del(head,2);
    print(head);
    
    return 0;
}

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;
}
posted @   Xuuxxi  阅读(102)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示