单链表的逆转

Ptr Reverse(Ptr head,int K)
{   cnt=1;
    new=head->next;
    old=new->next;
    while(cnt<K)
    {   tmp=old->next;
        old->next=new;
         new=old;
         old=temp;
         cnt++;
     }
     head->next->next=old;
     return new;
}

下面是有关程序代码:

Node * ReverseList(Node *head)
{
	Node *new,*old,*tmp;
	if(head==NULL||*head==NULL)
	return head;
	new=head;
	old=new->next;
	while(old)             //注意条件
	{
		tmp=old->next;	      //要改变old->next的指针,所以必须先保留old->next	     
		old->next=new;
		new=old;		      //循环往后
		old=tmp;
	}
	head->next=NULL;   //原先的head已经变成tail,别忘了置空,只有到这步才能置空
	*head=new;
	return head;
}

猜你喜欢

转载自blog.csdn.net/qq_42020563/article/details/80494536