第2章 线性表的链式表示
综合应用题 第1题
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct node {
ElemType data;
struct node *next;
}LNode, *LinkList;
bool InitList(LinkList &L){
L=NULL;
return true;
}
LinkList LinkListCreatH(ElemType *a,int n,LinkList &L) {
InitList(L);
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
L->data=a[0];
LNode *p;
for (int i = 1; i < n; i++){
p = (LNode *)malloc(sizeof(LNode));
if (p == NULL) {
printf("申请内存空间失败\n");
exit(0);
}
p->data = a[i];
p->next = L;
L=p;
}
return L;
}
LinkList LinkListCreatT(ElemType *a,int n,LinkList &L) {
InitList(L);
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
L->data=a[0];
LNode *p,*r;
r=L;
for (int i = 1; i < n; i++){
p = (LNode *)malloc(sizeof(LNode));
if (p == NULL) {
printf("申请内存空间失败\n");
exit(0);
}
p->data = a[i];
p->next = r->next;
r->next=p;
r=p;
}
return L;
}
void del_x(LinkList &L,ElemType x){
LNode *p;
if(L==NULL)return;
if(L->data==x)
{
p=L;
L=L->next;
delete p;
del_x(L,x);
}
else
del_x(L->next,x);
}
int main() {
LinkList list, start;
int array[8] = { 1, 2, 4, 3, 5, 6, 7, 8 };
cout<<"输出单链表的数据:";
LinkListCreatH(array,8,list);
for (start = list; start != NULL; start = start->next) {
cout<<start->data<<" ";
}
cout<<endl;
ElemType x;
cout<<"请输入要删除的元素的值:";
cin>>x;
del_x(list,x);
for (start = list; start != NULL; start = start->next) {
cout<<start->data<<" ";
}
cout<<endl;
return 0;
}
头插法
尾插法
|