全RE 刚开始学链表求助
查看原帖
全RE 刚开始学链表求助
1111873
qiufangguo楼主2024/7/19 09:56
#include<bits/stdc++.h>
using namespace std;
int q,n,sum=1,a;
struct Node{
	int data;
	Node *next;
}*head,*p,*r,*now;
void insert(Node *p,Node *r){//将p插到r后 
	p->next=r->next; //p先连上r的后一个节点 
	r->next=p; //r连上p 
}
Node * query(int x){
	now=head; //now在头指针开始搜索 
	while(now->next){ //下一个节点为空就退出循环 
		now=now->next; //now指针指向下一个节点 
		if(now->data==x){ //如果节点的数据等于要搜寻的数据 
			if(now->next==NULL)cout<<0<<endl; //如果下一个节点为空,证明是最后一个节点,输出0 
			else{
				now=now->next; //如果不是最后一个节点,now指针指向下一个节点 
				cout<<now->data<<endl;//query()函数返回的是指针?所以要自行引向data 
			}
			
		}
	}
}
Node * query1(int x){//查找位置(删除,插入锁定位置用) 
	now = head;
	while(now->next){
		now=now->next;
		if(now->data==x){
			return now;
		}
	}
}
void dele(Node *f){		   //删除 
	f->next=f->next->next; //节点直接和后一个节点相连 
}
int main(){
	head=new Node;
	r=head;
	p=new Node;
	head->next=r;
	p->data=1;
	p->next=NULL;
	r->next=p;
	r=p;
	cin>>q;
	for(int i=0;i<q;i++){
		cin>>n;
		if(n==1){		//插入 
			p=new Node; //新建一个节点 
			cin>>p->data; //输入新节点的数据
			cin>>a; //输入插入位置的数据 
			r=query1(a); //查找插入数据位置
			insert(r,p);//将p插到r后 
		}
		else if(n==2){ //查找 
			cin>>a;
			query(a);
		}
		else if(n==3){ //删除 
			cin>>a;
			p=query1(a);//获取节点位置 
			dele(p);
		}
	}
}
2024/7/19 09:56
加载中...