c++链表与C语言链表的主要区别:
在定义链表节点(结构体)之后,用class将其封装(封装相关函数以及一个结点指针,用来指向整个链表)。进而相关函数可通过使用该结点指针而减少函数形参的使用(递归函数除外)。
以下是结构体节点和class封装后的类:
struct node{ //链表节点
int data;
struct node*next;
};
class List{ //链表类
private: struct node*Head;
public: List();
void Create();
void Output();
void Find();
void Add();
void Delete();
};
以下是完整的代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct node{
int data;
struct node*next;
};
class List{
private: struct node*Head;
public: List();
void Create();
void Output();
void Find();
void Add();
void Delete();
};
List::List() {
Head = new node;
Head->next = NULL;
}
void List::Create(){
int n;
printf("请输入链表个数:");
scanf("%d",&n);
struct node*build;
struct node*tail;
int t=1;
printf("请依次输入链表数据:");
build=(struct node*)malloc(sizeof(struct node));
scanf("%d",&(build->data));
build->next=NULL;
Head=build;
tail=build;
while(t<n){
build=(struct node*)malloc(sizeof(struct node));
scanf("%d",&(build->data));
build->next=NULL;
tail->next=build;
tail=build;
t++;
}
}
void List::Output(){
struct node*first=Head;
while(first!=NULL){
cout<<first->data<<" ";
first=first->next;
}
}
void List::Find(){
int n=1,key;
printf("请输入要查找的数据:");
scanf("%d",&key);
struct node*p=Head;
while(p!=NULL&&(p->data!=key)){
p=p->next;
n++;
}
if(p==NULL) printf("不存在要查找的数 ");
else printf("要查找的数位于链表的第%d位 ",n);
}
void List::Add(){
int t=1,n,need;
printf("请输入要添加的元素:");
scanf("%d",&need);
printf("请输入要添加的元素的位置:");
scanf("%d",&n);
struct node*p=Head;
struct node*p1=NULL;
while(t<=n){
p1=p;
p=p->next;
t++;
}
struct node*addition;
addition=(struct node*)malloc(sizeof(struct node));
addition->data=need;
p1->next=addition;
addition->next=p;
}
void List::Delete(){
int key;
struct node*q;
printf("请输入你要删除的数:");
scanf("%d",&key);
struct node*p1=Head;
struct node*p2=NULL;
while(p1!=NULL&&(p1->data!=key)){
p2=p1;
p1=p1->next;
}
if(p1==NULL) printf("未找到要删除的数");
else{
q=p1;
p2->next=p1->next;
p1=p1->next;
free(q);
}
}
int main(){
List list1;
list1.Create();
list1.Output();
list1.Add();
list1.Output();
list1.Delete();
list1.Output();
list1.Find();
return 0;
}
- 还没有人评论,欢迎说说您的想法!