专栏文章
单链表
个人记录参与者 1已保存评论 0
文章操作
快速查看文章及其快照的属性,并进行相关操作。
- 当前评论
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @miofwzjx
- 此快照首次捕获于
- 2025/12/02 18:33 3 个月前
- 此快照最后确认于
- 2025/12/02 18:33 3 个月前
创建
CPPstruct Node{
int data;
Node *next;
};
int main(){
int n;
cin>>n;
Node *head=new Node;
Node *tail=head;
for(int i=0;i<n;i++){
Node *p=new Node;
cin>>p->data;
p->next=NULL;
tail->next=p;
tail=tail->next;
}
}
遍历
CPPstruct Node{
int data;
Node *next;
};
void display(Node *head){
Node *p=new Node;
p=head->next;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
}
查找
CPP#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
};
int found(Node *head,int n){
Node *p=new Node;
p=head->next;
int cnt=1;
while(p!=NULL){
if(p->data==n){
return cnt;
}
p=p->next;
cnt++;
}
return -1;
}
int main(){
Node *head=new Node;
Node *tail=head;
while(1){
int num;
cin>>num;
if(num==-1){
break;
}
Node *p=new Node;
p->data=num;
p->next=NULL;
tail->next=p;
tail=tail->next;
}
int n;
cin>>n;
cout<<found(head,n);
return 0;
}
封装后
CPP#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
};
void display(Node *head){
Node *p=head->next;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
}
void delete_num(Node *head,int x){
Node *s=new Node;
s=head->next;
Node *p=head;
while(s!=NULL){
if(s->data==x){
p->next=p->next->next;
delete s;
return ;
}
}
p=s;
s=s->next;
}
void insert_num(Node *head,int x,int y){
Node *p=new Node;
p=head->next;
while(p!=NULL){
if(p->data==x){
Node *s=new Node;
s->data=y;
s->next=p->next;
p->next=s;
}
p=p->next;
}
}
int main(){
Node *head=new Node;
Node *tail=head;
while(1){
int x;
cin>>x;
if(x==-1){
break;
}
Node *p=new Node;
p->data=x;
p->next=NULL;
tail->next=p;
tail=tail->next;
}
int a;
cin>>a;
delete_num(head,a);
display(head);
return 0;
}
相关推荐
评论
共 0 条评论,欢迎与作者交流。
正在加载评论...