C/C++基础 (linkedlist)

#include<stdio.h>
#include<string.h>

struct Student {
	int id;
	char name[16];
	Student* next;
};

Student ss[4] ={
	{201501,"john",0},
	{201502,"Jennifer", 0 },
	{201503,"AnXi", 0 },
	{201504,"Unnamed", 0 }
};

Student* find(Student* head, int id) {
	Student* p = head;
	while (p) {
		if (p->id == id) {
			return p;
		p = p->next;
		}
	return NULL;
	}
}
int main() {
	ss[0].next = &ss[1];
	ss[1].next = &ss[2];
	ss[2].next = &ss[3];
	ss[3].next = 0;

	Student* p = &ss[0];
	while (p) {
		printf("ID: %d, name: %s\n",p->id,p->name);
		p = p->next;	
	}
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct Student {
	int id;
	char name[16];
	Student* next;
};

Student m_head = { 0 };

void add1(Student* obj) {
	obj->next = m_head.next;
	m_head.next = obj;
}

void add2(Student* obj) {
	Student* p = &m_head;
	while (p->next) {
		p = p->next;
	}
	p->next = obj;
	obj->next = NULL;	
}

int main() { 
	Student* obj1 = (Student*)malloc(sizeof(Student));
	obj1->id = 12;
	strcpy(obj1->name,"X");
	add2(obj1);
	
	Student* obj2 = (Student*)malloc(sizeof(Student));
	obj2->id = 11;
	strcpy(obj2->name, "Y");
	add2(obj2);
	return 0;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct Student {
	int id;
	char name[16];
	Student* next;
};

Student m_head = { 0 };

int insert(Student* obj) {
	Student* cur = m_head.next;
	Student* pre = &m_head;
	while (cur) {
		if (obj->id < cur->id)
			break;
		pre = cur;
		cur = cur->next;
	}
	obj->next = pre->next;
	pre->next = obj;
	return 0;
}

void remove(int id) {
	Student* cur = m_head.next;
	Student* pre = &m_head;
	while (cur) {
		if (id == cur->id) {
			pre->next = cur->next;
			free(cur);
			break;
		}
		pre = cur;
		cur = cur->next;
	}
}
void show_all() {
	Student* obj = m_head.next;
	while (obj) {
		printf("%d, %s\n", obj->id, obj->name);
		obj = obj->next;
	}
}
int main() {
	Student* obj = NULL;

	obj = (Student*)malloc(sizeof(Student));
	obj->id = 1;
	strcpy(obj->name, "111");
	insert(obj);

	obj = (Student*)malloc(sizeof(Student));
	obj->id = 3;
	strcpy(obj->name, "333");
	insert(obj);

	obj = (Student*)malloc(sizeof(Student));
	obj->id = 4;
	strcpy(obj->name, "444");
	insert(obj);
	
	obj = (Student*)malloc(sizeof(Student));
	obj->id = 8;
	strcpy(obj->name, "888");
	insert(obj);
	obj = (Student*)malloc(sizeof(Student));
	obj->id = 5;
	strcpy(obj->name, "555");
	insert(obj);
	
	show_all();
	remove(5);
	printf("\n");
	show_all();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值