leetcode-206 翻转链表

 /*  wrong
if (head == NULL)
			return head;
		if (head->next == NULL)
			return head;
		ListNode*prev = head;
		ListNode*cur = head->next;

		ListNode*tail = head;
		while (cur->next!=NULL)
		{
			tail->next = cur->next;
			cur->next = prev;
			prev = cur;
			cur = cur->next;
		}
		tail->next = cur->next;
		cur->next = prev;
		head = cur;
		return head;*/
        
        
        /*right
        if (head == NULL || head->next == NULL)
			return head;

		ListNode*prev = head;
		ListNode*cur = head->next;
		ListNode*tail = cur->next;

		while (cur->next!=NULL)
		{
            #if 0
			cur->next = head;
			prev->next = tail;
			head = cur;
			cur = cur->next;//这样不行,由于cur->next已经指向head,所以cur = cur->next找不到下一个正确的位置,所以记录tail是cur->next的位置,用cur=tail
			tail = cur->next;
            			prev->next = tail;
			cur->next = head;

			head = cur;
			cur = tail;
			tail = cur->next;
		}

		cur->next = head;
		prev->next = tail;
        head=cur;
        return head;*/

        ListNode *prev=NULL;
        ListNode*curr=head;
        while(curr!=NULL)
        {
            ListNode *nextTmp=curr->next;
            curr->next=prev;
            prev=curr;
            curr=nextTmp;
        }
        return prev;
        //这个算法简洁,比我写的简单多了
public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}

递归我看了好久啊啊啊啊啊啊,这是我的理解,假设链表是[1, 2, 3, 4, 5]从最底层最后一个reverseList(5)来看
返回了5这个节点
reverseList(4)中
p为5
head.next.next = head 相当于 5 -> 4
现在节点情况为 4 -> 5 -> 4
head.next = null,切断4 -> 5 这一条,现在只有 5 -> 4
返回(return)p为5,5 -> 4
返回上一层reverseList(3)
处理完后返回的是4 -> 3
依次向上

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值