链表(1)

创造结点结构体

struct node {
    int data;
    struct node *next_;
};

尾插法输入数据

for(int i=1;i<=n;i++) {
        cin>>a;
        p=(struct node *)malloc(sizeof(struct node));
        p->data=a;
        p->next_=NULL;
        if(head==NULL) head=p;
        else q->next_=p;
        q=p;
    }

头插法(可实现逆序输出)

do {
        cin>>a;
        if(a!=-1) {
            p=(struct node *)malloc(sizeof(struct node));
            p->data=a;
            p->next_=head;
            head=p;
        }
    }while(a!=-1);//结束条件 

从顺序链表中插入一个数

cin>>a;//插入一个数 
    t=head;
    while(t!=NULL) {
        if(t->next_==NULL||t->next_->data>a) {
            p=(struct node *)malloc(sizeof(struct node));
            p->data=a;
            p->next_=t->next_;
            t->next_=p;
            break;
        }
        t=t->next_;
    }

删除顺序表的第k个数

int k;
    cin>>k;//删除第k个数
    int cnt=1;
    t=head;
    while(t!=NULL) {
        if(cnt==k) {
            t=t->next_;
            cnt++;
        }
        else {
            cout<<t->data<<' ';
            t=t->next_;
            cnt++;
        }
    } 

顺序输出模板

#include<iostream>
#include<algorithm>
using namespace std;
struct node {
    int data;
    struct node *next_;
};
int main() {
    struct node *head,*p,*q,*t;
    int n,a;
    cin>>n;
    head=NULL; 
    for(int i=1;i<=n;i++) {
        cin>>a;
        p=(struct node *)malloc(sizeof(struct node));
        p->data=a;
        p->next_=NULL;
        if(head==NULL) head=p;
        else q->next_=p;
        q=p;
    }
    t=head;
    while(t!=NULL) {
        cout<<t->data<<' ';
        t=t->next_;
    }
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/wes-/p/10753376.html
今日推荐