单链表的查找与修改

本次使用C++语言

#include <iostream>
using namespace std;
struct node{
	int num;
	node* next;
};
node* head,*now,*p;

int NodeNum;
node* create()
{
	int x;
	cout << "Please input NodeNum:";
	cin >> NodeNum;
	head=new node;
	now=head;
	for(int i=1;i<=NodeNum;i++)
	{
		cout<<"Please input number:";
		cin>>x;
		p=new node;
		p->num=x;
		now->next=p;
		now=p;
	}
	now->next=NULL;
	return head;
}

解析:

```
	p=new node;
	p->num=x;
	now->next=p;
	now=p;
```
p=new node;
为p申请一个节点
p->num=x;
为p中的数据域赋值
now->next=p;
另now的下一个结点指向p,第一次便是将头结点与p相连
now=p;
让now指针指到p指针指向的结点处

下一次再申请结点 继续同理操作 便形成了单向链表

主函数部分:

int main()
{
	int SearchNode;
	char YN;
	int Value;
	
	node* po;
	po=create();

	cout << "Please input SearchNode:";
	cin >> SearchNode;
	for (int i = 1; i <= SearchNode; i++)
	{
		po = po->next;
	}
	cout << po->num;
	cout << "是否进行修改(y/n):"<<endl;;
	cin >> YN;
	if (YN == 'y')
	{
		cout << "Please enter the revised value:";
		cin >> Value;
		po->num = Value;
	}
	cout << endl << endl;
	po = head->next;
	while (po != NULL)
	{
	cout << "num:" << po->num << endl;
	po = po->next;
	}
	return 0;
}

解析:

node* po;
	po=create();
定义结构体指针,是指针指向头结点,且头结点是数据域是没有数据的。
   

  for (int i = 1; i <= SearchNode; i++)
	    {
	    	    po = po->next;
     	}
前提是输入查找的结点数
然后让指针从头结点跳到对应的结点
cout << po->num;
cout << "是否进行修改(y/n):"<<endl;;
cin >> YN;
并输出 且提示是否修改

 po->num = Value;
 此处进行修改

修改后:

po = head->next;
	while (po != NULL)
	{
	cout << "num:" << po->num << endl;
	po = po->next;
	}
	另po指针从第一个有数据的结点开始输出数据

以上便是对单链表的查找并修改

最后,镇店之图:

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值