1. 程式人生 > >遞迴呼叫:連結串列中刪除元素不斷鏈現象

遞迴呼叫:連結串列中刪除元素不斷鏈現象

刪除的程式碼:

void del(NodeList &L, ElemType x){     NodeList p;     if(L!=NULL)         if(L->data==x){             p = L;             L=L->next;             free(p);             cout<<L<<endl;             del(L, x);//遞迴呼叫         }         else              del(L->next, x); }

 

完整de程式碼:

#include<iostream>
#include<stdlib.h>
using namespace std;

typedef int ElemType;
typedef struct Node{
	ElemType data;
	struct Node * next;
}Node, *NodeList;

//Create NodeList not mention NodeHead
NodeList createNodeList(){
	int num = 0, data = 0;
	NodeList s, p, node;
	cout<<"please input how many number you want to key in?"<<endl;
	cin>>num;
	for(int i=0;i<num;i++){
		cout<<"number "<<(i+1)<<":";
		cin>>data;
		if(i==0){
			node = (NodeList)malloc(sizeof(Node));
			node->data = data;
			node->next = NULL;
			p=node;
		}else{
			s = (NodeList)malloc(sizeof(Node));
			s->data = data;
			s->next = p->next;
			p->next = s;
			p = p->next;
		}
	}
	return node;
}
void print(NodeList node){
	NodeList p = node;
	while(p!=NULL){
		cout<<p->data<<" ";
		p = p->next;
	}
}

void del(NodeList &L, ElemType x){
	NodeList p;
	if(L!=NULL)
		if(L->data==x){
			p = L;
			L=L->next;
			free(p);
			cout<<L<<endl;
			del(L, x);
		}
		else 
			del(L->next, x);
}

int main(void){
	NodeList node = createNodeList();
	print(node);
	del(node, 2);
	cout<<endl;
	print(node);
	return 0;
}