栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

链表的基本操作笔记

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

链表的基本操作笔记

直接上代码
头插法和尾插法都有,归并没写。。。不过也不难,具体还得看题目情况,基本操作的笔记就不写了

#include 
using namespace std;
struct node
{
	int data;
	node* next;
};
int n;
node* onCreate(int Array[])
{
	node* p,*pre, *head;
	head = new node;
	head->next = NULL;
	pre = head;
	for (int i = 0 ;i < n ;i++)
	{
		p = new node;
		p->data = Array[i];
		p->next = NULL;
		pre->next = p;
		pre = p;
		
	}
	return head;
}
//搜索
void search(node* head,int x)
{
	node* p = head;
	p = p->next;
	while (p != NULL)
	{
		if (p->data == x)
			cout << "成功! " << p->data << endl;
		p = p->next;
	}
}
//插入
//pos是插入节点的位置,x是要插入节点的数据是多少
void insert(node* head, int pos,int x)
{
	node* p = head;
	node* temp = new node;
	temp->data = x;
	int count = 0;
	p = p->next;
	if (pos > n)
	{
		cout << "tnnd,逗我玩是吧!" << endl;
		return;
	}
	while (p != NULL)
	{
		if (count == pos - 1)
		{
			temp->next = p->next;
			p->next = temp;
		}
		p = p->next;
		count++;
	}
	n++;
}
//删除
void del(node* head,int x)
{
	node* p = head->next;
	node* pre = head;
	p = p->next;
	while (p != NULL)
	{
		if (x == p->data)
		{
			pre->next = p->next;
			delete(p);
			p = pre->next;
		}
		else 
		{
			pre = p;
			p = p->next;
		}
	}
}
//遍历
void Trave(node* head)
{
	node* p = head;
	p = p->next;
	while (p != NULL)
	{
		cout << p->data << " ";
		p = p->next;
	}
}
int main()
{
	cin >> n;
	int data[10];
	node* head;
	for (int i = 0; i < n; i++)
	{
		cin >> data[i];
	}
	head = onCreate(data);
//	search(head, 2);
//	insert(head, 10, 8);
//	insert(head, 3, 8);
//	del(head, 3);
	Trave(head);
	return 0;
}

search函数测试结果

insert函数测试结果

del函数测试结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/691217.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号