删除单链表中某元素的前驱元素

#include <iostream>
#include <iomanip>
#include <string.h>
#include <cmath>
#include <algorithm>//算法头文件
#include <fstream>
#include <cstdlib>
#include <vector>
#include <sstream>
using namespace std;

//无头结点单链表 
struct Node{
	int data;	//数据域 
	Node *next; //指针域 
};

//初始化单链表,即创建头指针
Node* init(){
	Node *head = new Node;
	head->data = 0;
	head->next = NULL;
	return head;
} 

//头插法
void insertList(Node *head, int ele){
	Node *cur = new Node;	//为新节点申请内存空间 
	cur->data = ele;	//赋值数据域 
	cur->next = head->next;	//头插法,头指针指向新节点,新节点指向原来的头结点,变成新的头结点 
	head->next = cur;	
} 

//创建单链表,插入几个值
void create(Node *head, int low, int high){
	for(int i=low; i<=high; i++){
		insertList(head, i);
	}
} 

//打印链表
void print(Node *head){
	//因为要移动指针,所以用一个指针指向,保留原来数据不变
	Node *p = head->next; //p指向链表
	while(p != NULL){
		cout<<p->data<<"  ";
		p = p->next;
	} 
	cout<<endl;
} 

//删除链表中某元素前面的元素 
void DeletePrElement(Node* head, int ele){
	Node* pr2 = head; //头指针位置
	Node* pr1 = head->next; //第一个节点位置 
	Node* p = head->next->next; //第二个节点位置,即传进来的元素
	while(p != NULL){
		if(p->data == ele){ //删除前一位置节点 
			pr2->next = p;
			delete pr1;
			return ;
		}else{
			pr2 = pr2->next;
			pr1 = pr1->next;
			p = p->next;
		}
	} 
}

int main(){
	
	Node *head = init();
	
	insertList(head, 10);
	
	create(head, 1, 10);
	
	print(head);
	
	DeletePrElement(head,6);
	print(head);
	
	return 0;
}
发布了167 篇原创文章 · 获赞 52 · 访问量 6944

猜你喜欢

转载自blog.csdn.net/qq_42363032/article/details/103766834