#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node{
int num;
struct Node *next;
};
struct Node* init_head();
int insert_Node(struct Node *head,int new_value);
int print_Node(struct Node *head);
int free_Node(struct Node* head);
struct Node* sort_Node(struct Node* head);
struct Node* get_middle_node(struct Node* head);//快慢指针得到中间结点
int main(int argc, char *argv[])
{
struct Node* head = NULL;
head = init_head();
if(!head){
return 0;
}
insert_Node(head,5);
insert_Node(head,4);
insert_Node(head,3);
insert_Node(head,2);
insert_Node(head,1);
printf("first print:\n");
print_Node(head);
printf("sort print:\n");
head = sort_Node(head);
print_Node(head);
free_Node(head);
return 0;
}
struct Node* init_head()
{
struct Node *head = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
if(!head){
printf("malloc head fail\n");
return NULL;
}
memset(head,0,sizeof(struct Node));
head->next = NULL;
return head;
}
int insert_Node(struct Node *head,int new_value)
{
if(!head){
printf("the head is NULL\n");
return 1;
}
struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
if(!new_node){
printf("malloc new node fail\n");
return 1;
}
memset(new_node,0,sizeof(struct Node));
new_node->num = new_value;
new_node->next = head->next;
head->next = new_node;
return 0;
}
int print_Node(struct Node *head)
{
if(!head){
printf("the head is NULL\n");
return 1;
}
struct Node *cur_node = head->next;
while(cur_node){
printf("the value:%d\n",cur_node->num);
cur_node = cur_node->next;
}
return 0;
}
int free_Node(struct Node *head)
{
if(!head){
printf("the head is NULL\n");
return 1;
}
struct Node *cur_node = head->next,*tmp = NULL;
while(cur_node){
tmp = cur_node;
cur_node = cur_node->next;
free(tmp);
}
free(head);
head = NULL;
return 0;
}
/*
思路:在原有链表的基础上,从第一个有实际意义的结点开始,依次改变指针的指向,最后再让头指针指向原来链表的最后一个数据
就能形成一条新的链表。
其中要注意的是原来链表的第一个有实际意义的结点应该是新链表的最后一个结点,因此应该指向NULL。
每次改变指针的指向时应注意前后顺序。
*/
struct Node* sort_Node(struct Node* head)
{
struct Node *p = head->next ,*q = NULL ,*tmp = NULL;
head->next = NULL;
while(p){
tmp = p->next;
p->next = q;
q = p;
p = tmp;
}
head ->next = q;
return head;
}
struct Node* get_middle_node(struct Node* head)
{
struct Node *slow = NULL,*fast = NULL;
if (head == NULL || head->next == NULL)
return NULL;
slow = head;
fast = head;
while(fast->next != NULL && fast->next->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
return slow->next;
}