单链表

· · 个人记录

创建

struct 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;
  }
}

遍历

struct 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;
    }
}

查找

#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;
}

封装后

#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;
}