且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

史上最简单的C语言链表实现,没有之一

更新时间:2021-08-02 15:30:35

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define  NR(x)   (sizeof(x)/sizeof(x[0]))

struct node 
{
	int data ; 
	struct node *next ; 
};

void top_append_list(struct node *head , int value);
void print_link(struct node head);
void tail_append_list(struct node *head , int value);
int  delete_link_node(struct node *head , int number);
int  sort_link_node(struct node *head , int flag );    //flag = 1  s->b   0  b->s   
void turn_over_node(struct node *head);

int main(void)
{
	int array[] = {1,2,5,4,3,8,7,6,9};

	struct node head = {.next = NULL} ;  
	struct node *headp ; 

	int i ; 
	for(i = 0 ; i < NR(array) ; i++)
	{
		tail_append_list(&head , array[i]);
	}

	print_link(head);
	int num ; 
	sort_link_node(&head , 1);
	print_link(head);

	//b -> s
	sort_link_node(&head , 0);
	print_link(head);

	turn_over_node(&head);
	print_link(head);

	return 0 ; 
}


void top_append_list(struct node *head , int value)
{
	struct node *New = NULL ; 
	New = malloc(sizeof(struct node));
	if(NULL == New){
		fprintf(stderr , "分配失败!\n");
		return ;
	}	

	New->data = value ; 

	New->next = head->next ; 
	head->next = New ; 
}

void print_link(struct node head)
{
	struct node *tmp = head.next ; 
	while(tmp)
	{
		printf("%d " , tmp->data);
		tmp = tmp->next ; 
	}
	putchar('\n');
}
void tail_append_list(struct node *head , int value)
{
	struct node *New = NULL ; 
	

	New = malloc(sizeof(struct node ));
	if(NULL == New){
		fprintf(stderr , "分配失败!\n");
		return ;
	}
	New->data = value ;  		
	struct node *tmp = head ;   
	while(tmp->next && (tmp = tmp->next)) ; 
	
	
	New->next = tmp->next ; 
	tmp->next = New ; 
}

int  delete_link_node(struct node *head , int number)
{
	struct node *after = head->next , *before = head; 
	int flag = 0 ; 
	while(after)
	{
		if(after->data == number)
		{
			flag = 1 ; 
			before->next = after->next ; 
			after->next = NULL ;
			free(after);
			after = before->next ; 
			continue ; 
		}
		after = after->next; 
		before = before->next ; 
	}
	return flag ; 
}

int  sort_link_node(struct node *head , int flag )    //flag = 1  s->b   0  b->s  
{
	int tmp ; 
	
	struct node *tmp1 , *tmp2 ; 

	tmp1 = head ; 
	while(tmp1 = tmp1->next)
	{
		tmp2 = tmp1->next ; 
		while(tmp2)	
		{
			if((flag==1)?(tmp1->data > tmp2->data):(tmp1->data < tmp2->data))			
			{
				memcpy(&tmp , &tmp1->data , sizeof(int));
				memcpy(&tmp1->data , &tmp2->data , sizeof(int));
				memcpy(&tmp2->data , &tmp , sizeof(int));
			}
			tmp2 = tmp2->next ; 
		}
	}

}

void turn_over_node(struct node *head)
{
	struct node *tmp = head->next ; 
	struct node *cur = NULL; 
	head->next = NULL ; 

	while(cur = tmp)	
	{
		tmp = tmp->next ; 
		cur->next = head->next ; 
		head->next = cur ; 
	}
}