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;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值