链表逆置函数

插入法,将原链表的链节依次往新链表的最前端插入

typedef struct res {
	int num;
	res* next;
}res;
res* reverse(res* start)
{
	if ((start->next)->next == NULL) { return start; }
	res* temp, * p;
	p = start->next;
	start->next= NULL;
    while (p != NULL)
	{
		temp = p;
		p = p->next;
		temp->next =start->next;
		start->next = temp;
		
	}
	
	return start;
}
int main()
{
	res* head, * mid,*end,*p;
	head = new res;
	end = head;
	mid = new res;
	int i = 1;
	while (i < 10)
	{
		mid = new res;
		mid->num = i;
		end->next = mid;
		end = mid;
		i++;
		
	}
	end->next = NULL;
	p = head->next;
	while (p!= NULL)
	{
		cout << p->num;
		p = p->next;
	}
	cout << endl;
	res* k=reverse(head);
	res* ps;
	ps = k->next;
	while (ps != NULL)
	{
		cout << ps->num;
		ps = ps->next;
	}
}

你可能感兴趣的:(链表逆置函数)