206.翻转链表
思路:对于对于一个单向链表,顺序访问每个点直到尾端,然后递归回归输出转向链表
代码:
class Solution {
public:
void rev(ListNode *pre,ListNode *now,ListNode* &head)
{
if (now->next!=NULL) {//是否是尾节点
rev(now, now->next,head);//不是,下层递归
now->next=pre;//转换本层指向
}
else{
head=now;//是尾节点,将当前尾节点置首
now->next=pre;//转换本层指向
}
}
ListNode* reverseList(ListNode* head) {
if (head==NULL) {//排除空表
return head;
}
rev(NULL, head,head);
return head;
}
};

浙公网安备 33010602011771号