线性表-4-单链表查找并删除节点

#include 
#include 
using namespace std; 

typedef struct LNode{
     
	int data;
	struct LNode *next;
}LNode;

/*尾插法*/ 
void createLNodeR(LNode *&L,int arr[],int n){
     
	LNode *r,*s;
	int i;
	
	L = (LNode*)malloc(sizeof(LNode));
	L->next = NULL;
	
	r = L;
	
	for(i=0;i<n;i++){
     
		s = (LNode*)malloc(sizeof(LNode));
		s->data = arr[i];
		r->next = s;
		r = r->next;
	}
	r->next = NULL;
}

/*头插法*/
void createLNodeL(LNode *&L,int arr[],int n){
     
	LNode *s;
	int i;
	
	L = (LNode*)malloc(sizeof(LNode));
	L->next = NULL;
	
	for(i=0;i<n;i++){
     
		s = (LNode*)malloc(sizeof(LNode));
		s->data = arr[i];
		s->next = L->next;
		L->next = s;
	}
}

/*查找是否存在元素x,存在则删去并返回1,不存在返回0*/
int findAndDelete(LNode *L,int x){
     
	LNode *p,*q;
	
	p=L;
	while(p->next!=NULL){
     
		if(p->next->data==x)
			break;
		p = p->next;
	}
	
	if(p->next == NULL)
		return 0;
	q = p->next;
	p->next = q->next;
	free(q);
	
	return 1;
} 

int main(int argc, char** argv) {
     	
	int arr[4] = {
     1,2,3,4};
	LNode *L,*l;
	createLNodeR(L,arr,4);
	l=L;
	findAndDelete(L,2);
	for(int i=0;i<6;i++){
     
		cout<<l->data<<"..";
		l = l->next;
	}

	return 0;
}

你可能感兴趣的:(线性表-4-单链表查找并删除节点)