非常无聊的单链表,实现了增加,释放,排序等非常基础的内容
基础链表:
#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;
}