2.6-14对于不带头结点的单链表 L,设计一个递归算法返回第一个值为 x 的结点的地 址,没有这样的结点时返回 NULL
程序员文章站
2024-03-21 16:19:28
...
2.6-14对于不带头结点的单链表 L,设计一个递归算法返回第一个值为 x 的结点的地址,没有这样的结点时返回 NULL
#include "LinkList.cpp"
#include <bits/stdc++.h>
LinkNode *Firstxnode(LinkNode *&L,int x){
if(L == NULL)
return NULL;
if(L->data == x)
return L;
else
Firstxnode(L->next,x);
}
int main(){
int a[] = {1,2,5,2,3,2};
LinkNode *L,*p;
int n = sizeof(a) / sizeof(a[0]);
L = CreateList(a,n);
DispList(L);
int x = 3;
p = Firstxnode(L,x);
cout << endl << "该值为:" << p->data;
Release(L);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef struct Node {
int data;
struct Node *next;
} LinkNode;
LinkNode *CreateList(int a[],int n) {
if(n < 0)
return NULL;
LinkNode *head = (LinkNode *)malloc(sizeof(LinkNode));
LinkNode *p = (LinkNode *)malloc(sizeof(LinkNode));
p = head;
head->data = a[0];
int i = 0;
for(i = 1; i < n; i++) {
LinkNode *node = (LinkNode *)malloc(sizeof(LinkNode));
node->data = a[i];
p->next = node;
p = node;
}
p->next = NULL; // 尾结点next域置为空
return head;
}
void DispList(LinkNode *ln) {
cout << " ";
if(ln != NULL){
cout << ln->data;
DispList(ln->next);
}
}
void Release(LinkNode *ln) {
if(ln->next == NULL)
return ;
else {
Release(ln->next);
free(ln);
}
}