一些简单的链表算法二

下面的算法是稍微有点难度的

1、在一个给定的已按升序排列的链表插入一个给定的节点

void SortedInsert(LIST**headRef,LIST*newNode)
{
	if(*headRef == 0 || (*headRef)->data >= newNode->data)
	{
		newNode->next = *headRef;
		*headRef = newNode;
	}
	else
	{   LIST *current = *headRef;
		while(current->next != 0 && current->next->data < newNode->data)
		{
				current = current->next;
		}
		newNode->next = current->next;
		current->next = newNode;
	}
}

2、将给定的链表按升序排列

void InsertSort(LIST**headRef)
{
	LIST* result = 0;
	LIST* next = 0;
	LIST* current = *headRef;
	while(current != 0)
	{   next = current->next;
		SortedInsert1(&result,current);
		current = next;
	}
	*headRef = result;
}

3、将给定的两个链表连接起来

void Append(LIST**headRefa,LIST**headRefb)
{
	LIST* current = *headRefa;
	if(current == 0)
	{
		*headRefa = *headRefb;
			}
	else
	{
		while(current->next != 0)
		{
			current = current->next;
		}
		current->next = *headRefb;
	}
        *headRefb = 0;
}

4、将链表分成前后两个链表,如果有奇数个节点则前面比后面多一个 

void FrontBackSplit(LIST** head,LIST**a,LIST**b)
{
	int len = Length(*head);
	LIST* current = *head;
	*a = *head;
	*head = 0;
	if(len % 2 == 0)
	{   
		if(len == 0)
		{
			*b = 0;
		    return;
		}
		else
		{   len = len/2;
			while(--len)
			{
				current = current->next;
			}
		}
		
	}
	else
	{  
		len = len/2;
		while(len--)
		{
			current = current->next;
		}
	}
	*b = current->next;
	current->next = 0;
}

5、将一个按升序排列的链表的重复元素删除 

void RemoveDuplicates(LIST* head)
{
    if(head == 0)
		return;
	else
	{
		LIST*current1 = head;
		LIST*current2 = current1->next;
		while(current1 != 0 && current2 != 0)
		{
			if(current2->data == current1->data)
			{
				current1->next = current2->next;
			    delete(current2);
				current2 = current1->next;
			}
			else
			{
				current1 = current1->next;
				current2 = current2->next;
			}
		}
	}
}

6、将一个链表的第一个元素插入到另一个链表的头部

void MoveNode(LIST**destRef,LIST**sourceRef)
{
    assert(*sourceRef);
	LIST *current = *sourceRef;
	*sourceRef = current->next;
	current->next = *destRef;
	*destRef = current;
}

  

  

 

posted @ 2012-12-27 14:29  ying870510  阅读(231)  评论(0编辑  收藏  举报