連結串列:插入,刪除,顯示,排序
#include <stdio.h>
#include <stdlib.h>
typedef struct stu{
int value;
struct stu *next;
}Node;
//連結串列中的插入,顯示,刪除,排序
Node *insert_head(Node *head,int value);
void show(Node *head);
Node *del(Node *head,int value);
Node *sort(Node *head);
int main()
{
Node *head = NULL;
head = insert_head(head,30);
head = insert_head(head,20);
head = insert_head(head,70);
head = insert_head(head,10);
head = insert_head(head,80);
head = insert_head(head,90);
show(head);
head = sort(head);
show(head);
return 0;
}
Node *insert_head(Node *head,int value){
Node *tmp = NULL;
tmp = (Node *)malloc(sizeof(Node));
tmp->value = value;
tmp->next = NULL;
if(head== NULL){
head = tmp;
}
else{
tmp->next = head;
head = tmp;
}
return head;
}
void show(Node *head){
while(head != NULL)
{
printf("%d\n",head->value);
head = head->next;
}
}
Node *del(Node *head,int value){
Node *tmp = head;
Node *pre = NULL;
Node *cur = head;
while((cur != NULL) && (cur->value != value))
{
pre = cur;
cur = cur->next;
}
//tail
if(cur == NULL){
printf("NO this value:%d\n",value);
}//head
else if(cur == head)
{
tmp = head->next;
free(head);
}
else{
pre->next = cur->next;
free(cur);
}
return tmp;
}
Node *sort(Node *head){
if(head == NULL || head->next ==NULL)
return head;
Node *tmp ;
Node *min;
Node *min_pre = NULL;
Node *newhead = NULL;
while(head)
{
tmp = head;
min = head;
while(tmp->next != NULL)
{
if(tmp->next->value > min->value)
{
min_pre = tmp;
min = tmp->next;
}
tmp = tmp->next;
}
if(min == head)
{
head = head->next;
}
else{
min_pre->next = min->next;
}
if(newhead == NULL)
{
newhead = min;
min->next = NULL;
}else{
min->next = newhead;
newhead = min;
}
}
return newhead;
}