递归调用:链表中删除元素不断链现象
删除的代码:
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;
}