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