链表反转(双指针法和递归法)

如题目所示,链表的反转一般有两种方法
可以参照LeetCode题目进行观看
题目要求:反转一个链表

           https://leetcode-cn.com/problems/reverse-linked-list/
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

1.双指针法
思路:1. 定以结点 pre = null; cur = head;
2.将head 后移 (head = head.next), cur 指向 pre(cur.next = pre ;) ;然后pre,cur后移到它两的下一跳(pre = cur;cur =head)

在这里插入图片描述

3.若head ==null;则循环结束,链表已经反转完毕。返回pre。
在这里插入图片描述
代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* reversePrint(struct ListNode* head, int* returnSize){
                struct   ListNode *pre=NULL;
                struct   ListNode*cur=head;
               
                int Nodesum=0;
                while(head!=NULL)    //链表反转
                {
                    head=head->next;
                    cur->next=pre;
                    pre=cur;
                    cur=head;
                }
                return  pre;

2.递归法
满足递归的三个条件
1.大问题拆成两个子问题
2.子问题求解方式和大问题一样
3.存在最小子问题
所以能够递归;

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
if(head==NULL||head->next==NULL)
{
    return head;
}
struct ListNode*p=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return p;
}

}


双指针点作者:水山文墨
链接:https://blog.csdn.net/qq_43411521

递归作者:tangweiqun
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-pin-jiang-jie-die-dai-he-di-gui-hen-hswxy/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值