#include <stdio.h>
#include <stdlib.h>
struct node
{
int val;
int hao;
struct node *next;
};
void showlist(struct node *h)//遍历
{
printf("============\n");
while(h->next)
{
printf("hao %d val %d\n", h->next->hao, h->next->val);
h = h->next;
}
}
void insert_head(struct node *h, struct node *n)//头插
{
n->next = h->next;
h->next = n;
}
void insert_Head(struct node **h, struct node *n)//头插
{
n->next = *h;
*h = n;
}
void insert_tail(struct node *h, struct node *n)//尾插
{
while(h->next)
{
h = h->next;
}
h->next = n;
}
void insert_Tail(struct node **h, struct node *n)//尾插
{
while((*h))
{
h = &((*h)->next);
}
*h = n;
}
struct node* find_list(struct node *h, int n, struct node newlist)//查找
{
while(h->next->val == n)
{
struct node *tmp = h->next;
h->next = h->next->next;
tmp->next = NULL;
insert_tail(&newlist, tmp);
}
struct node *p = h->next;
while(p->next)
{
if(p->next->val == n)
{
struct node *t = p->next;
struct node *tmp = p->next;
p->next = t->next;
tmp->next = NULL;
insert_tail(&newlist, tmp);
}else
{
p = p->next;
}
}
return newlist.next;
}
struct node* sort_list(struct node *h, struct node newsort)//排序
{
struct node *p = h->next;
struct node *min = NULL;
struct node *minprev = NULL;
struct node *t = NULL;
while(p)
{
minprev = NULL;
t = p;
min = t;
while(t->next)
{
if(min->val > t->next->val)
{
minprev = t;
min = t->next;
}else
{
t = t->next;
}
}
if(min == p)
{
p = p->next;
}else
{
minprev->next = min->next;
}
min->next = NULL;
// insert_head(&newsort, min);
insert_tail(&newsort, min);
}
return newsort.next;
}
void destroy(struct node **h)
{
struct node *p = NULL;
while(*h)
{
p = (*h)->next;
free(*h);
*h == NULL;
*h = p;
}
}
int main ()
{
struct node head;
int arr[] = {8,8,1,2,8,3,8,8,4,8,8};
int i = 0;
struct node *newnode = NULL;
head.next = NULL;
while(i < sizeof(arr)/sizeof(int))
{
newnode = malloc(sizeof(struct node));
newnode->val = arr[i];
newnode->hao = i;
newnode->next = NULL;
// insert_head(&head, newnode);
// insert_head(&(head.next), newnode);
// insert_tail(&head, newnode);
insert_Tail(&(head.next), newnode);
i++;
}
showlist(&head);
// struct node newlist;
// newlist.next = NULL;
// newlist.next = find_list(&head, 8, newlist);
// showlist(&newlist);
// showlist(&head);
//排序
struct node newsort;
newsort.next = NULL;
newsort.next = sort_list(&head, newsort);
showlist(&newsort);
destroy(&(head.next));//销毁
return 0;
}