數據結構—單鏈表的排序以及逆置

1、單鏈表排序:

單鏈表的排序中,只需要交換兩個節點的值即可,不需要改變指向

<span style="font-family:SimSun;font-size:18px;">typedef struct student
{
	int data;
	struct student *next;
}node;
//head指向表頭,head->next纔是第一個節點
void sort(node *head)
{
	node *p=head->next;
	int len=length(head);
	int temp;
	while(p==NULL || p->next==NULL)
		return;
	for (int i=1;i<len;i++)
	{
		p=head->next;
		for (int j=0;j<len-i;j++)
		{
			if (p->data>p->next->data)
			{
				//值的交換
				temp=p->data;
				p->data=p->next->data;
				p->next->data=temp;
			}
			p=p->next;
		}
	}
}</span>


2、單鏈表逆置

設置輔助指針,用於記錄先前遍歷的結點


//head指向表頭,head->next纔是第一個節點

<span style="font-family:SimSun;font-size:18px;">void reverse(node *head)
{
	node *p1,*p2,*p3;
	p1=head->next;
	if(p1==NULL || p1->next==NULL)
		return;
	p2=p1->next;
	while(p2)
	{
		p3=p2->next;
		p2->next=p1;
		p1=p2;
		p2=p3;
	}
	head->next->next=NULL;
	head->next=p1;
}</span>



還有一種逆置方法是使用遞歸,在對當前結點逆置時,先遞歸地逆置其後繼結點,然後將後繼結點指向當前結點。

詳情見:http://blog.csdn.net/heyabo/article/details/7610732

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