C語言單鏈表反轉

#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;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章