PTA实验题11-2-9链表逆置-递归
struct ListNode *reverse( struct ListNode *head )
{
if(head == NULL || head->next == NULL)
{
return head;
}
struct ListNode *newNode = reverse(head->next);
/*出递归后,head为进入递归之前的值*/
head->next->next = head;//5->next == 6,5->next-next <==>6->next = 5
head->next = NULL;
return newNode;//链表逆置的头
}
非递归
//非递归
struct ListNode *reverse( struct ListNode *head)
{
if(head == NULL || head->next == NULL)
{
return head;
}
struct ListNode *p= head, *newH = NULL;//p遍历,newH新节点
while(p)
{
struct ListNode *temp = p->next;//temp指向p所在节点的下一个节点
p->next = newH;
newH = p;
p = temp;
}
return newH;
}
tips:
1.非递归的思想为新建一个链表,将旧链表移动过去;
2.可以用原来的头指针遍历,但不建议这么做,应养成良好的习惯,避免头指针的滥用。所以在递归解法中为我的做法道歉。