时间:2021-07-01 10:21:17 帮助过:18人阅读
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
while(head -> next)
{
pre = head;
head = head -> next;
head -> next = pre;
}
return head;
};理由如下:在反转过程中,head ->next 已经反向,无法继续向后遍历,因此增加一个指针采用3个指针完成操作
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
while(head)
{
ListNode* next = head -> next;
head -> next = pre;//head是尾结点,指针置空
head = next;
pre = head;
}
return pre; //head = NULL
};递归不会,参考Discuss后,理解。
思路如下:通过递归使得头结点不断向后遍历,直到终止条件:达到尾结点 后停止。
代码如下:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//终止条件,达到尾结点停止
if(head == NULL || head ==NULL)
return head;
else
{
//头结点向后移动
ListNode* temp = reverList(head->next);
head->next->next = head; //1
head->next = NULL; //2
}
return temp;
};到达递归终止条件时呈现的状态如下:
返回上一层递归后状态如下:
经过注释1、2的两行代码后,状态如下
可见head结点的位置与递归层数有关,而temp作为反转后的头结点,位置始终不动,从而达到反转效果。
递归代码虽能看懂,然而我现在还并不会设计,还是个菜鸡。
相关文章:
PHP实现单链表翻转操作示例
以上就是使用递归和非递归实现单链反转详解的详细内容,更多请关注Gxl网其它相关文章!