1. 程式人生 > >兩種方法(遞迴,非遞迴)實現單鏈表的逆轉

兩種方法(遞迴,非遞迴)實現單鏈表的逆轉

//普通方法實現連結串列的逆置
void reverseList(pNode *head)
{
	pNode p, q, r;
	if (*head == NULL || (*head)->next == NULL)
		return;
	q = *head;
	p = q->next;
	r = NULL;
	while (p){
		q->next = r;
		r = q;
		q = p;
		p = p->next;
	}
	q->next = r;
	*head = q;
}

//遞迴法實現連結串列的逆置
pNode reverseList_reverse(pNode head)
{
	pNode current_head, head_next;
	if (head == NULL)
		return NULL;
	
	if (head->next == NULL)//邊界條件
		return head;
	else{
		current_head = head;//記下當前的頭結點a0
		head_next = head->next;//記下當前頭結點後面的結點a1
		head = reverseList_reverse(head_next);//返回(a1...an)逆轉後的頭結點
		head_next->next = current_head;//用上面儲存的地址(逆轉後的尾結點)指向原來的頭結點a0
		current_head->next = NULL;//將a0的next域置零
	}
	return head;//返回a0
}