C/C++---单向链表

摘要

闲来无聊,写个链表玩玩

代码

主要功能有:

  • 创建链表头
  • 创建新链表
  • 添加新链表
  • 显示链表
  • 查找链表
  • 更改链表
  • 删除链表

list.h

#pragma once
#include <iostream>
using namespace std;

//信息区
struct INFO
{
	string name;
	int age;
};

//链表部分
struct LIST
{
	INFO info;
	struct LIST* next;
};

list.c

#include "list.h"

LIST *listhead;//创建链表头

/*创建链表头*/
void create_head(void)
{
	listhead = new LIST;
	listhead->next = NULL;
}
/*创建新链表*/
LIST* create_newlist(INFO data)
{
	LIST* newlist = new LIST;
	newlist->info = data;
	newlist->next = NULL;
	return newlist;
}
/*添加新链表--头插 or 尾插*/
void add_newlist(LIST* head, INFO data)
{
	LIST* temphead = head;
	LIST* newlist = create_newlist(data);
	/*头插----start*/
	while (temphead->next != NULL)
	{
		temphead = temphead->next;
	}
	temphead->next = newlist;
	newlist->next = NULL;
	/*头插----end*/

	///*尾插----start*/
	//head->next = newlist;
	//newlist->next = temphead->next;
	///*尾插----end*/
}

/*显示链表*/
int show_list(LIST* head)
{
	int num = 0;
	LIST* temphead = head->next;
	while (temphead)
	{
		cout << temphead->info.name << "\t" << temphead->info.age << endl;
		temphead = temphead->next;
		num++;
	}
	return num;
}
/*查找链表*/
LIST* seek_list(LIST* head, char* name)
{
	int flag = 0;
	LIST* temphead = head->next;
	while (temphead != NULL)
	{
		if (name == temphead->info.name)
		{
			flag = 1;
			break;
		}
		temphead = temphead->next;		
	}
	if(flag == 1)
		return temphead;
	return NULL;
}

/*更改链表*/
void change_list(LIST* head, char* name, char *newname)
{
	LIST* temphead = seek_list(head, name);
	if (temphead)
	{
		temphead->info.name = newname;
		cout << "修改成功" << endl;
		return;
	}
	cout << "没有该联系人,修改失败" << endl;
}
/*删除链表*/
void delete_list(LIST* head, char* name)
{
	int flag = 0;
	LIST* temphead1 = head;
	LIST* temphead2 = head->next;

	while (temphead2 != NULL)
	{
		if (temphead2->info.name == name)
		{
			flag = 1;
			break;
		}
		temphead1 = temphead2;
		temphead2 = temphead2->next;
	}
	if (flag == 1)
	{
		temphead1->next = temphead2->next;
		delete temphead2;
		cout << "删除成功" << endl;
	}
	else
	{
		cout << "查无此人" << endl;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值