C++链表常用操作

#include <iostream> 
#include<stdlib.h>
#include <iomanip>
using namespace std;

struct node//1、定义链表
{
	int num;
	node *next;
};
void Makelist(node*&head) //2、创建链表
{
	node *p=NULL, *s;
	s = new node;
	cin >> s->num;
	while (0!= s->num)
	{
		if (head == NULL)
		{
			head = s;
		}
		else
		{
			p->next=s;
		}
		p = s;
		s = new node;
		cin >> s->num;
	}
	p->next = NULL;
	delete s;
};
void chatouwei(node*&head) //3、头前插进新节点和尾后插进新节点
{
	//头前插进
	node *t = NULL, *p, *temp;//临时储存;
	t = new node;
	cout << "请输入你的头前新节点值!" << endl;
	cin >> t->num;
	t->next = head;
	head = t;

	//尾后插进
	cout << "请输入你的尾后新节点值!" << endl;
	t = new node;
	cin >> t->num;
	temp = t;
	p = head;
	while (p->next!=NULL)
	{
		p = p->next;
	}
	p->next = temp;
	temp->next = NULL;
	t = new node;//解:如果新建delete s的话相当delete t导致链表连不上
	delete t;
}
void chapqianxin(node*&head) //4、在某个节点前面插入新节点;
{
	node *p = NULL, *q = NULL, *s=NULL, *w=NULL; int n;;
	
	cout << "请选择你的节点值" << endl;
	cin >> n;
	for (p = head, q = p->next; q;p=q,q=q->next)
	{
		if (head->num==n)//判断头节点
		{
			cout << "请输入你的新节点值" << endl;
			s = new node;
			cin >> s->num;
			s->next = head;
			head = s;
			break;
		}
		if (q->num == n)//判断下一节点
		{
			cout << "请输入你的新节点值" << endl;
			s = new node;
			cin >> s->num;
			w = s;
			p->next = w;
			w->next = q;
			s = new node;//解:如果新建delete s的话相当delete w导致链表连不上
			delete s;
			break;
		}
	}
}
void chaphouxin(node*&head) //5、在某个节点p后面插入新节点;
{
	node *p = NULL, *s = NULL, *w; int n;;
	p = head;
	cout << "请选择你的节点值" << endl;
	cin >> n;
	while (p)
	{
		if (p->num==n)
		{
			cout << "请输入你的新节点值" << endl;
			s = new node;
			cin >> s->num;
			w = s;
			w->next = p->next;
			p->next = w;
			s = new node;
			break;
		}
		p = p->next;
	}
	delete s;
}


void deletehead(node*&head) //6编写删除头节点方法
{
	node *h = head;
	head = head->next;
	delete h;
}

void deletenode(node*&head) //7、删除某个节点
{
	node *p=NULL,*q;
	int n;
	cout << endl;
	cout << "请输入你的节点值" << endl;
	cin >> n; 
	for (p = head, q = p->next; q;p=q,q=q->next)
	{ 
		if (p->num==n)
		{
			node *h = head;
			head=head->next;
			delete h;
			break;
		}
		if (q->num==n)
		{
			p->next = q->next;
			delete q;
			break;
		}
	}
};
void showlist(node*&head) //8、输出链表
{
	node *h = head;
	while (h)
	{
		cout << h->num << ends;
		h=h->next;
	}	
};
void main()
{
	node *head = NULL;
	Makelist(head);//创建链表
	chatouwei(head);//头前插进新节点和尾后插进新节点
	chapqianxin(head);//在某个节点前面插入新节点;
	chaphouxin(head);//在某个节点p后面插入新节点;
	deletehead(head);//编写删除头节点方法
	deletenode(head);//删除某个节点
	showlist(head);//输出链表
}

这一切廓然开朗,这一切原来如此,舒服,加油!!!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值