zhao_ry514114
赵若伊

导航

 
#include<bits/stdc++.h>
using namespace std;
struct Node{
	int data;
	struct Node *next;
};
Node *head = NULL;
void add(int x){
	if(head != NULL){
		Node *a = new Node;
		a->data = x;
		a->next = NULL;
		Node *p = head;
		while(p->next != NULL){
			p = p->next;
		}
		p->next = a;
	}
	else{
		head = new Node;
		head->data = x;
		head->next = NULL;
	}
}
void insert(int n, int x){
	Node *a = new Node;
	a->data = x;
	a->next = NULL;
	if(n==1){
		a->next = head;
		head = a;
	}
	else{
		Node *p = head;
		for(int i = 1; i <= n - 2; i++){
			p = p->next ;
			if(p == NULL)break;
		}
		if(p == NULL)cout<<"位置有误"<<endl;
		else{
			a->next = p->next ;
			p->next = a;
		} 
	}
}
void deldata(int data){
	Node *p = head, *pre = NULL;
	while(p != NULL){
		if(data == p->data ){
			if(p == head){
				head = p->next;
			}
			else{
				pre->next = p->next ;
			}
			delete p;
			break;
		}
		pre = p;
		p = p->next ;
	}
}
void delpos(int n){
	Node *p = head, *t;
	if(n == 1){
		if(head != NULL){
			head = head->next ;
			delete p;
		}
		else{
			cout<<"空链表"<<endl;
		}
	}
	else{
		for(int i = 1;i <= n - 2;i++){
			p = p->next;
			if(p == NULL)break;
		}
		if(p == NULL || p->next == NULL){
			cout<<"位置有误"; 
		}
		else{
			t = p->next ;
			p->next = t->next ;
			delete t;
		}
	}
}
void print(){
	Node *p = head;
	while(p != NULL){
		cout<<p->data<<" ";
		p = p->next ;
	}
	cout<<endl;
}
int main(){
	int order, x, p;
	cout<<"输出指令:";
	while(true){
		cout<<"1.追加,2.插入,3.删除值,4.删位置,5.显示,0.停止"<<endl;
		cin>>order;
		if(order == 1){
			cin>>x;
			add(x);
			print();
		}
		else if(order == 2){
			cin>>p>>x;
			insert(p,x);
			print();
		}
		else if(order == 3){
			cin>>x;
			deldata(x);
			print();
		}
		else if(order == 4){
			cin>>x;
			delpos(x);
			print();
		}
		else if(order == 5){
			print();
		}
		else{
			break;
		}
	}
	return 0;
}
posted on 2025-08-25 21:26  zhao_ry514114  阅读(7)  评论(0)    收藏  举报