链表常见操作算法

链表常见操作算法

1. 单链表的逆置

node *Reverse(node *Head)
{
	node *p1,*p2,*p3;
	
	if(head == NULL || head->next == NULL)
	{
		return head;
	}
	
	p1 = head,p2 = p1->next;
	while(p2)
	{
		p3 = p2->next;
		p2->next = p1;			// 指针域反转
		
		p1 = p2;				// 遍历调整
		p2 = p3;		
	}
	
	head->next = NULL;
	head = p1;
	
	return head;
}


2. 单链表排序

node *Sort(node *Head)
{
	node *p, *p2,*p3;
	int n = length(Head);	// 得到链表长度
	int temp;
	
	if(head = NULL || head->next == NULL)
	{
		return head;
	}
	
	p = head;
	
	for(int j = 1; j < n; ++ j)
	{
		p = Head;
		for(int i = 0; i < n - j; ++ i)
		{
			if( p->data > p->next->data )
			{
				temp    	  = p->data;
				p->data		  = p->next->data;
				p->next->data = temp;
			}
			p = p->next;
		}
	}	
	return head;
}

3. 链表的插入(自动排序)

node *Insert_Sort(node *Head, int num)
{
	node *p0, *p1, *p2;
	p1 = Head;
	p0 = (node *)malloc( sizeof(node) );
	p0->data = num;
	
	while( (p0->data > p1->data) && (p1->next != NULL) )
	{
		p2 = p1;
		p1 = p1->next;
	}
	
	if( p0->data <= p1->data )
	{
		if(Head == p1)			// 插在头结点之前
		{
			p0->next = p1;
			Head = p0;
		}
		else					// 调整指域
		{
			p2->next = p0;
			p0->next = p1;
		}
	}
	else						
	{
		p1->next = p0;
		p0->next = NULL;
	}
	return (Head);
}

4. 链表结点删除

node *Delete_Node(node *Head, int num)
{
	node *p1,*p2;
	p1 = Head;
	
	while(num != p1->data && p1->next != NULL)
	{
		p2 = p1;
		p1 = p1->next;
	}
	
	if(num == p1->data)
	{
		if(Head == p1)
		{
			Head = p1->next;
			free(p1);
		}
		else
			p2->next = p1->next;
	}
	else
		printf("Can't find node->num!'");
	
	return Head;
	
	return (Head);
}
    原文作者:fanwenjieok
    原文地址: https://blog.csdn.net/fanwenjieok/article/details/38793843
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞