数据结构复习
总代码部分
#include<stdio.h>
#include<malloc.h>
typedef struct node{
int data;
struct node *next;
}Node;
Node* Init(){
Node *list;
list = (Node*)malloc(sizeof(Node));
list->next = NULL;
return list;
}
int len(Node *list){
int length=0;
while(list->next != NULL){
length++;
list = list->next;
}
return length;
}
void add(Node *list,int data,int flag){
int length;
length = len(list);
for(int i= 0;i<flag;i++){
list = list->next;
}
Node *p;
p = Init();
p->data = data;
p->next = list->next;
list->next = p;
}
void del(Node* list,int flag){
for(int i = 0;i<flag;i++){
list = list->next;
}
Node *p;
p = Init();
p = list->next;
list->next = p->next;
free(p);
}
Node* insertionSortList(Node *list);
int main(){
int n;
Node *list;
int length,data;
list = Init();
scanf("%d",&n);
for(int i = 0;i < n;i++){
scanf("%d",&data);
add(list,data,i);
}
list = insertionSortList(list);
length = len(list);
for(int i = 0;i<length;i++){
list = list->next;
printf("%5d",list->data);
}
return 0;
}
Node* insertionSortList(Node *list){
Node *newstarnode,*temp;
newstarnode = Init();
temp = Init();
newstarnode->next = NULL;
list = list->next;
while(list!=NULL){
temp = list->next;
Node *newl;
newl = Init();
newl = newstarnode ;
while(newl->next != NULL && newl->next->data<list->data){
newl = newl->next;
}
list->next = newl->next;
newl->next = list;
list = temp;
}
free(temp);
free(newl);
return newstarnode;
}
排序部分函数解析
首先创建一个新的列表,循环旧列表,将旧列表分别于新表元素相比,当比到比新表数据大时,将旧表的节点插入。
Node* insertionSortList(Node *list){
Node *newstarnode,*temp;
newstarnode = Init();
temp = Init();
newstarnode->next = NULL;
list = list->next;
while(list!=NULL){
temp = list->next;
Node *newl;
newl = Init();
newl = newstarnode ;
while(newl->next != NULL && newl->next->data<list->data){
newl = newl->next;
}
list->next = newl->next;
newl->next = list;
list = temp;
}
free(temp);
free(newl);
return newstarnode;
}