链表test

非常无聊的单链表,实现了增加,释放,排序等非常基础的内容
基础链表:

#include<cstdio>
#include<iostream>
using namespace std;
struct node{
    int val;
    node*next1;
    node():next1(0){};
}*head=new node();//head为虚拟头指针,仅为了方便起见
node*find(int i)//i为需要查找的数值
{
    node*pos=head;
    while(pos->val!=i)pos=pos->next1;
    return pos;
}
void add(int x)//x为需要插入的数值
{
    node*pos=head;
    while(pos->next1)
        pos=pos->next1;
    node*t=new node();pos->next1=t;
    t->val=x;
}
void delete1(node*pos)//递归释放整个链表
{
    if(pos->next1){
        delete1(pos->next1);
    }
    delete []pos;
}
void print(void)
{
    for(node*p=head->next1;p;p=p->next1)
        cout<<p->val<<' ';
    cout<<endl;
}
int main()
{
    int i;
    while(cin>>i&&i)add(i);
    print();
    add(6);print();
    add(100000);print();
   delete1(head);//print();

    return 0;
}

选择排序:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
    int val;
    node*next1;
    node():next1(0){};
};
node*head=new node();
void add(int x)
{
    if(!head){
        head->val=x;return;
    }
    node*pos=head;
    while(pos->next1)
        pos=pos->next1;
    node*t=new node();pos->next1=t;t->val=x;
    return;
}
int main()
{
    int i,j;
    while(cin>>i&&i)add(i);
    node*p,*q;
    for(p=head;p;p=p->next1){
        for(q=p->next1;q;q=q->next1){
            if(p->val>q->val){
                swap(p->val,q->val);
            }
        }
    }
    p=head;
    while(p->next1){
        cout<<p->val<<' ';p=p->next1;
    }
    cout<<p->val<<endl;

    return 0;
}

合集By Poeroz:

#include <cstdio>
#include <algorithm>
using namespace std;

struct node
{
    int val;
    node *next;
};

node* makeList()
{
    node *head = new node;
    head->val = 0;
    head->next = NULL;
    node *last = head;
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        node *p = new node;
        scanf("%d", &p->val);
        p->next = NULL;
        last->next = p;
        last = p;
    }
    return head;
}

void sort(node *head)
{
    for (node *p1 = head->next; p1 != NULL; p1 = p1->next)
        for (node *p2 = p1->next; p2 != NULL; p2 = p2->next)
            if (p2->val < p1->val)
                swap(p1->val, p2->val);
}   

void print(node *head)
{
    for (node *p = head->next; p != NULL; p = p->next)
        printf("%d ", p->val);
    puts("");
}

void del(node *p)
{
    if (p->next != NULL)
        del(p->next);
    delete p;
}

int main()
{
    node *HEAD = makeList();
    sort(HEAD);
    print(HEAD);
    del(HEAD);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值